Austin Green
Austin Green

Reputation: 37

Unable to replace characters in a String

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?

Upvotes: 3

Views: 1168

Answers (6)

CodeChimp
CodeChimp

Reputation: 8154

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.

Upvotes: 0

AlexR
AlexR

Reputation: 115328

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

Upvotes: 0

Woot4Moo
Woot4Moo

Reputation: 24316

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

Upvotes: 0

Perception
Perception

Reputation: 80593

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

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499790

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

Upvotes: 12

Michał Šrajer
Michał Šrajer

Reputation: 31182

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

Upvotes: 5

Related Questions