StringEscapeHelper { public String escape(String str) { StringBuilder escaped = null; int offset = 0; for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); char r = (c < escapeMap.length) ? escapeMap[c] : NO_REPLACEMENT; if (r != NO_REPLACEMENT) { if (escaped == null) { escaped = new StringBuilder(str.length() + 1); } escaped.append(str, offset, i); escaped.append('\\'); escaped.append(r); offset = i + 1; } } if (escaped == null) { return str; } if (offset < str.length()) { escaped.append(str, offset, str.length()); } return escaped.toString(); } StringEscapeHelper(char... replacementPairs);  StringEscapeHelper(boolean unescapeUnicodeEscapes, char... replacementPairs); String unescape(String str); String escape(String str);  }
@Test public void specialCharsAreEscaped() { StringEscapeHelper escapeHelper = new StringEscapeHelper( 'n', '\n', 't', '\t', 'x', '!' ); String escaped = escapeHelper.escape("\thello\nworld!"); assertThat(escaped, is("\\thello\\nworld\\x")); }
@Test public void stringWithoutSpecialCharsIsNotModified() { StringEscapeHelper escapeHelper = new StringEscapeHelper( 'n', '\n', 't', '\t', 'x', '!' ); String escaped = escapeHelper.escape("hello world"); assertThat(escaped, is("hello world")); }