Skip to content

Instantly share code, notes, and snippets.

@oowekyala
Created January 22, 2020 05:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oowekyala/741cab7e54b8040d1f0356a66e327552 to your computer and use it in GitHub Desktop.
Save oowekyala/741cab7e54b8040d1f0356a66e327552 to your computer and use it in GitHub Desktop.
Escape routines for java text
class JavaEscapeUtil {
/**
* Replaces unprintable characters by their escaped (or unicode escaped)
* equivalents in the given string
*/
public static String escapeJava(String str) {
StringBuilder retval = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
final char ch = str.charAt(i);
switch (ch) {
case 0:
break;
case '\b':
retval.append("\\b");
break;
case '\t':
retval.append("\\t");
break;
case '\n':
retval.append("\\n");
break;
case '\f':
retval.append("\\f");
break;
case '\r':
retval.append("\\r");
break;
case '\"':
retval.append("\\\"");
break;
case '\'':
retval.append("\\'");
break;
case '\\':
retval.append("\\\\");
break;
default:
if (ch < 0x20 || ch > 0x7e) {
String s = "0000" + Integer.toString(ch, 16);
retval.append("\\u").append(s.substring(s.length() - 4));
} else {
retval.append(ch);
}
break;
}
}
return retval.toString();
}
}
@oowekyala
Copy link
Author

See https://gist.github.com/uklimaschewski/6741769 for the reverse conversion (escaped -> unescaped)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment