Search code examples
javareplaceall

Replace one set of characters with another set of characters


I am writing code to convert Roman Numbers to Decimal Numbers.

I was wondering if this line could be optimised?

String s = "MCMXCIV";
String code = s.replaceAll("I", "a")
               .replaceAll("V", "b")
               .replaceAll("X", "c")
               .replaceAll("L", "d")
               .replaceAll("C", "e")
               .replaceAll("D", "f")
               .replaceAll("M", "g");

Expected value of code: gegceab

EDIT 1: Can the same code can be written in a shorter way?

EDIT 2:

Two conditions I want

  1. Avoid expensive string concatenation
  2. replace each character with corresponding code in O(1)

Solution

  • I have no idea how this helps you translate roman numbers to decimal numbers, but, sure, this can be simplified!

    For starters, .replace does this job strictly better ('replaceAll is a stupid name; the first argument is a regular expression. replace, without the all, also replaces all, and takes an actual raw string, which is what you wanted – java doesn't like breaking backwards compatibility; the silly name is unlikely to be corrected).

    Secondly, 'shorter' is mostly meaningless. The relevant goals when writing code are readability and flexibility, and rarely efficiency (performance); shorter is on its own not a relevant goal.

    Here's an alternative take; it's significantly more efficient for large strings. For small strings, it's 2020, the time taken is going to round down to 0.

    private static final String LETTERS = "IVXLCDM";
    
    char[] cs = s.toCharArray();
    for (int i = 0; i < cs.length; i++) {
        cs[i] = 'a' + LETTERS.indexOf(cs[i]);
    }
    String code = new String(cs);