REPLACEMENT OF ENGLISH NUMBERS OF A STRING WITH ROMAN NUMBERS USING JAVA

Ida B Wells

Total Post:30

Points:210
Posted by  Ida B Wells
Java 
 930  View(s)
Ratings:
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?

  1. Garry Winogrand

    Post:24

    Points:168
    Re: Replacement of English numbers of a string with Roman numbers using java

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

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!