Home > DeveloperSection > Forums > Replacement of English numbers of a string with Roman numbers using java
Ida B Wells
Ida B Wells

Total Post:30

Points:210
Posted on    October-14-2013 3:43 AM

 Java Java 
Ratings:


 1 Reply(s)
 672  View(s)
Rate this:

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 mainText. What is wrong with my code?



Garry Winogrand
Garry Winogrand

Total Post:24

Points:168
Posted on    October-14-2013 4:08 AM

This 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 Strings are immutable objects. You don't perform in-place replacement to it.

You do it like this:

StringBuffer buffer = new StringBuffer();
while (m.find()) {
    String tmp = m.group();
    char[] cTmp = tmp.toCharArray();
    for (int j = 0; j < cTmp.length; j++) {
        cTmp[j] = (char) (cTmp[j] + 1584);  // You don't need to typecast `cTmp[j]` to `int`.
    }
    m.appendReplacement(buffer, new String(cTmp));
}
m.appendTail(buffer);
System.out.println(buffer.toString());

Don't want to miss updates? Please click the below button!

Follow MindStick