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 Answers 3
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.
Comments
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
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.
abbr[i][1]withpairs[i][1]...Also, use aMap<String,String>instead of bidimentional array...