3

I am trying to go through an array of characters and replace that character in the string with the parallel character in the other 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 and example of what I get:

Enter a string: as the dog runs here
Output: as the dog runs here

It always outputs the same string with no replacements.

I also tried using:

myCopy.replace('a','@');

and

myCopy.replace("a","@");

and the replaceAll method.

Any suggestions?

6 Answers 6

12

Strings are immutable in Java. replace() doesn't change the string you call it on - it returns a new string with the changes. So you want:

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

(The same is true for all the methods on String which "appear" to be changing it, as it's immutable.)

Sign up to request clarification or add additional context in comments.

Comments

5

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 string, change it as long as you need and then generate an immutable String as a result via toSting().

1 Comment

Thank you so much. So simple I never even realized it.
0

Strings are immutable. So in your for loop your operation is not having any tangible effect. You need to assign the result of replace back to the original variable:

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

Comments

0

The reason why this is not working is that you are not assigning the returned String value to the array. This:

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

Needs to become:

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

Comments

0

You are confused with String and replace(). String is immutable, i.e. you cannot change its state. Calling replace() creates copy of source string and returns it. Do something like this:

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

Comments

0

As Michal said, Strings are immutable. If this is being used in a process that is more intensive, you may want to use StringBuffer instead. StringBuffer is mutable, however it will take some additional work as it doesn't have a directly comparable replace() method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.