可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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
EDIT: My apologies, I should clarify the question. I have no control over what 'x' is going to be, it may be a string I read from a file. I would like for x to retain its escape characters during normal program execution, but for debugging purposes I would like to see the actual escape characters.
Writing a method that subs each and every escape character seems overkill. Isn't there a better printing library other than PrintStream that does this for me?
If you're familiar with Ruby, think x.inspect()
回答1:
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))
.
回答2:
Use the method "StringEscapeUtils.escapeJava" in Java lib "org.apache.commons.lang"
String x = "hello\nworld"; System.out.print(StringEscapeUtils.escapeJava(x));
回答3:
You have to escape the slash itself:
String x = "hello\\nworld";
回答4:
Just escape the escape character.
String x = "hello\\nworld";
回答5:
System.out.println("hello \\nworld");
回答6:
Java has its escape-sequence just the same as that in C. use String x = "hello\\nworld";
回答7:
Try to escape the backslash like \\n
回答8:
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.