Java – How to rewrite this block of code using a StringBuilder in Java

javastringstringbuilder

Given a word, I've to replace some specific alphabets with some specific letters such as 1 for a, 5 for b etc. I'm using regex for this. I understand that StringBuilder is the best way to deal with this problem as I'm doing a lot of string manipulations. Here is what I'm doing:

String word = "foobooandfoo";
String converted = "";
converted = word.replaceAll("[ao]", "1");
converted = converted.replaceAll("[df]", "2");
converted = converted.replaceAll("[n]", "3");

My problem is how to rewrite this program using StringBuilder. I tried everything but I can't succeed. Or using String is just fine for this?

Best Solution

I think this is a case where clarity and performance happily coincide. I would use a lookup table to do the "translation".

  public static void translate(StringBuilder str, char[] table)
  {
    for (int idx = 0; idx < str.length(); ++idx) {
      char ch = str.charAt(idx);
      if (ch < table.length) {
        ch = table[ch];
        str.setCharAt(idx, ch);
      }
    }
  }

If you have a large alphabet for the str input, or your mappings are sparse, you could use a real map, like this:

  public static void translate(StringBuilder str, Map<Character, Character> table)
  {
    for (int idx = 0; idx < str.length(); ++idx) {
      char ch = str.charAt(idx);
      Character conversion = table.get(ch);
      if (conversion != null) 
        str.setCharAt(idx, conversion);
    }
  }

While these implementations work in-place, you could create a new StringBuilder instance (or append to one that's passed in).