Reputation: 2421
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.
Upvotes: 27
Views: 63566
Reputation: 454
The following code produces octal escape sequences. Modify the replacement function to produce what you need.
Pattern
.compile ("[^\\p{Graph}]")
.matcher ("A\tB\nC")
.replaceAll
(
(final MatchResult r)
-> String .format ("\\\\%03o", + r .group () .charAt (0)))
Another possibility would be to use String .format ("^%c", r .group () .charAt (0) + '@')
—but it will only handle control characters.
Upvotes: 0
Reputation: 398
Use the method "StringEscapeUtils.escapeJava" in Java lib "org.apache.commons.lang"
String x = "hello\nworld";
System.out.print(StringEscapeUtils.escapeJava(x));
Upvotes: 39
Reputation: 12019
You might want to check out this method. Although this may do more than you intend. Alternatively, use String replace methods for new lines, carriage returns and tab characters. Do keep in mind that there are also such things as unicode and hex sequences.
Upvotes: -1
Reputation: 18633
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))
.
Upvotes: 17
Reputation: 14781
Java has its escape-sequence just the same as that in C.
use String x = "hello\\nworld";
Upvotes: 1
Reputation: 6322
You have to escape the slash itself:
String x = "hello\\nworld";
Upvotes: 2