I'm going to find number chars in a String and replace them with their Roman versions. The Code is:
public static void main(String[] args) {
String pattern = "[0-9]+";
Pattern p = Pattern.compile(pattern);
String mainText = "34titi685dytti5685fjjfj8585443";
Matcher m = p.matcher(mainText);
int i = 0;
while (m.find()) {
System.out.println("Match number " + i);
String tmp = m.group();
char[] cTmp = tmp.toCharArray();
for (int j = 0; j < cTmp.length; j++) {
cTmp[j] = (char) ((int) cTmp[j] + 1584);
}
m.group().replaceFirst(tmp,new String(cTmp));
i++;
}
System.out.println(mainText);
}
But at the end it prints the same string main text. What is wrong with my code?
Anonymous User
14-Oct-2013This is not how you do a replacement using Matcher. m.group() just gives you the matched part of the string. Whatever replacement you do in it, you have to perform concatenation with original string. This is due to the fact that Stringsare immutable objects. You don't perform in-place replacement to it.
You do it like this: