Efficient way to replace escape sequences when building a String in Java



I have requirement replacing the escape sequences [n, r, t] to “.” when building the String. I am using StringBuilder to append multiple strings.

For Example

public class TempClass {

    public static void main(String[] args) throws IOException, ScriptException {
        StringBuilder sb = new StringBuilder();
        String s1 = "This is Johnn He is good guy";
        String s2 = " Another String";
        System.out.println(sb.append(s1).append(s2).toString().replaceAll("[\r\n\t\f]","."));
    }
}

The above code is working fine.. My question is, is there any efficient way to do this without affecting the performance ? I worry about replaceAll will cause performance issue. I may need to replace all each and every String I need to append.

Answer

Nothing fancier that this is required. How you want to package the two strings is up to you. I put them in an array. I also arranged the conditional tests in the order of most to least expected in an attempt to trigger the conditional asap. This order could be different depending on the environment that generated the strings.

StringBuilder sb = new StringBuilder();

String s1 = "This is Johnn He is good guy";
String s2 = " Another String";

for(String str : new String[]{s1,s2}) {
   for (char ch : str.toCharArray()) {
      if (ch == 'n' || ch == 'r' || ch == 't'||ch == 'f') {
          continue; // skip this character
      }
      sb.append(ch);
   }
}
System.out.println(sb.toString());


Source: stackoverflow