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?

+3


source to share


6 answers


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.)

+12


source


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 () .

+5


source


Strings are immutable. Therefore, in your for loop, your operation has no perceptible effect. You need to assign the result replace

back to the original variable:

for(int y = 0; y < first.length; y++) {
    myCopy = myCopy.replace(first[y],second[y]);
}

      

0


source


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]); 
    }

      

0


source


You are confused with String

and replace()

. The string is immutable, i.e. You cannot change her state. The call replace()

creates a copy of the original string and returns it. Do something like this:

String replacedString = myCopy.replace(first[y],second[y]);

0


source


As Michal said, the strings are immutable. If this is used in a more intensive process, you can use StringBuffer instead. StringBuffer has changed, however it will require additional work as it has no comparable method replace()

.

0


source







All Articles