When I have a string such as:
String x = "hello\nworld";
How do I get Java to print the actual escape character (and not interpret it as an escape character) when using System.out?
For example, when calling
System.out.print(x);
I would like to see:
hello\nworld
And not:
hello
world
I would like to see the actual escape characters for debugging purposes.
解决方案
One way to do this is:
public static String unEscapeString(String s){
StringBuilder sb = new StringBuilder();
for (int i=0; i
switch (s.charAt(i)){
case '\n': sb.append("\\n"); break;
case '\t': sb.append("\\t"); break;
// ... rest of escape characters
default: sb.append(s.charAt(i));
}
return sb.toString();
}
and you run System.out.print(unEscapeString(x)).