如何在Java中打印转义字符 [英] How do I print escape characters in Java
问题描述
当我有一个字符串如:
String x = "hello\nworld";
如何让Java打印实际的转义字符(而不是将其解释为转义字符)什么时候使用System.out?
How do I get Java to print the actual escape character (and not interpret it as an escape character) when using System.out?
例如,当调用时
System.out.print(x);
我希望看到:
hello\nworld
而不是:
hello
world
编辑:
我很抱歉,我应该澄清这个问题。我无法控制'x'是什么,它可能是我从文件中读取的字符串。我希望x在正常程序执行期间保留其转义字符,但出于调试目的,我希望看到实际的转义字符。
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.
编写一个方法而且每个逃脱角色都有点矫枉过正。是否有比PrintStream更好的打印库为我这样做?
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?
如果您熟悉Ruby,请考虑x.inspect()
If you're familiar with Ruby, think x.inspect()
推荐答案
一种方法是:
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();
}
你运行 System.out.print(unEscapeString (x))
。
这篇关于如何在Java中打印转义字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!