Last active
May 7, 2024 19:51
-
-
Save oowekyala/741cab7e54b8040d1f0356a66e327552 to your computer and use it in GitHub Desktop.
Escape routines for java text
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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: | |
retval.append("\\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(); | |
} | |
} |
Hey thank you so much, is it okay if I use this in a uni project/assignment?
I will include references to the original. If not, all good :).
Also I may be reading the code incorrectly, but at https://gist.github.com/oowekyala/741cab7e54b8040d1f0356a66e327552#file-javaescapeutil-java-L12 wouldn't you use \\0
?
Sure, go ahead.
Yeah you're right it should output \0
Thanks.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See https://gist.github.com/uklimaschewski/6741769 for the reverse conversion (escaped -> unescaped)