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.
We have many escape characters in Python like \n, \t, \r, etc., What if we want to print a string which contains these escape characters? We have to print the string using repr() inbuilt function. It prints the string precisely what we give.
Use the method "StringEscapeUtils.escapeJava" in Java lib "org.apache.commons.lang"
String x = "hello\nworld"; System.out.print(StringEscapeUtils.escapeJava(x));
One way to do this is:
public static String unEscapeString(String s){ StringBuilder sb = new StringBuilder(); for (int i=0; i<s.length(); 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))
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With