-1

I am replacing all vowels in a String with a char using a for loop.

public String replaceVowel(String text, char letter)
{
    char ch;
    for(int i = 0; i<text.length(); i++)
    {
        ch = text.charAt(i);
        if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'y')
        {
            ch = letter;
        }   
        text.charAt(i) = ch;
    }
    return text;
}

The code trips on an error on line:

text.charAt(i) = ch;

In this line I am attempting to initialize the char at the loop's location of the string. However the line produces the error:

The left-hand side of an assignment must be a variable

Any help is appreciated!

sid_mac
  • 151
  • 2
  • 10
  • Read the error. The left side is the assignee, the right is the assigning value. You can't logically assign a char value to a char value. You meed to assign it to a char *variable* – Andrew Li Oct 06 '16 at 22:41
  • Strings in Java are immutable. You may want to use a character array or a [`StringBuilder`](https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html#setCharAt-int-char-). – 4castle Oct 06 '16 at 22:43
  • 1
    `return text.replaceAll("[aeiouy]", String.valueOf(letter));` – 4castle Oct 06 '16 at 22:46

2 Answers2

2

As oppsed to C++, Java method call never return a variable "reference" (like C++ reference) so you can never assign a method call result.

Also Java string is immutable, which means you cannot change individual characters in a string without creating a new string. See this post Replace a character at a specific index in a string? on this topic.

Community
  • 1
  • 1
SwiftMango
  • 15,092
  • 13
  • 71
  • 136
0

charAt(index) returns the character in that index. It cannot be used for assigning values.

Something like this would work:

char ch;
        String text = "hailey";
        char letter = 't';
        char[] textAsChar = text.toCharArray();
        for(int i = 0; i<text.length(); i++)
        {
            ch = text.charAt(i);
            if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'y')
            {
                ch = letter;
            }   
            textAsChar[i] = ch;
        }
        System.out.println(String.valueOf(textAsChar));
HARDI
  • 394
  • 5
  • 12