Can't replace characters in string
I am trying to loop through a character array and replace that character in a string with a parallel character in another array.
private String replace(String input)
{
char[] first = {'a','e','o','s'};
char[] second = {'@','3','0','$'};
String myCopy = input.toLowerCase();
for(int y = 0; y < first.length; y++)
{
myCopy.replace(first[y],second[y]);
}
return myCopy;
}
Here's an example of what I get:
Enter a string: as the dog runs here
Output: as the dog runs here
It always outputs the same line without any substitutions.
I have also tried using:
myCopy.replace('a','@');
and
myCopy.replace("a","@");
and the replaceAll method.
Any suggestions?
source to share
Strings are immutable in Java. replace()
does not change the line you call it on - it returns a new line with the changes. So you want:
myCopy = myCopy.replace(first[y], second[y]);
(The same is true for all methods on String
that "appear" to modify it, since they are immutable.)
source to share
String.replace () will return a new string. Strings are immutable in java.
What you are looking for is probably StringBuilder . You can build it from a string, modify it as long as you like, and then create an immutable string as a result of toSting () .
source to share
The reason this doesn't work is because you are not assigning a String return value to an array. It:
for(int y = 0; y < first.length; y++)
{
myCopy.replace(first[y],second[y]);
}
You need to become:
for(int y = 0; y < first.length; y++)
{
myCopy = myCopy.replace(first[y],second[y]);
}
source to share