0

I have a two dimensional array that contains pairs of strings. If one string is found it should replace it with its pair.

The code:

 for (int i = 0; i < pairs.length; i++) {
        if (name.contains(pairs[i][0])) {
            name.replaceAll(pairs[i][0], abbr[i][1]);
        }
    }

It is not replacing the strings. What is the error?

3
  • Some sample input & expected output may help. As well as "review" it is case for replace() (or) replaceAll()? and last but not least, Strings are immutable. Commented Aug 29, 2012 at 20:51
  • Replace abbr[i][1] with pairs[i][1]...Also, use a Map<String,String> instead of bidimentional array... Commented Aug 29, 2012 at 20:52
  • I don't really get the question... Could you post the contents of the array BEFORE you run your code, and the desired contents of the array AFTER you run your code? Commented Aug 29, 2012 at 20:53

3 Answers 3

4

You are neglecting to assign the result of replaceAll, and so the modification is lost.

Perhaps you want to keep the modified string as name:

for (int i = 0; i < pairs.length; i++) {
    if (name.contains(pairs[i][0])) {
        name = name.replaceAll(pairs[i][0], abbr[i][1]);
    }
}

Note that java String objects are immutable, so calling name.replaceAll doesn't modify name, it returns a new String with the modifications.

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

Comments

2

String is immutable.

name.replaceAll(pairs[i][0], abbr[i][1]);

creates a new String (it doesn't modify the "name" String)

Try

name = name.replaceAll(pairs[i][0], abbr[i][1]);

Comments

0

A modified version of the string is being created, however it's return value is being lost.

name = name.replaceAll(pairs[i][0], abbr[i][1]);

should work.

2 Comments

I don't think the string is being modified. A new one is created with the modification and being passed back.
Thank you. I didn't realize I had written it that way! Edited my answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.