[英]How do I print escape characters in Java?
当我有一个字符串,如:
String x = "hello\nworld";
使用System.out
时,如何使Java打印实际的转义符(而不将其解释为转义符)?
例如,当打电话时
System.out.print(x);
我想看看:
hello\nworld
并不是:
hello
world
我希望看到用于调试目的的实际转义符。
在Java库“ org.apache.commons.lang”中使用方法“ StringEscapeUtils.escapeJava”
String x = "hello\nworld";
System.out.print(StringEscapeUtils.escapeJava(x));
一种方法是:
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))
。
您必须逃脱斜线本身:
String x = "hello\\nworld";
只要逃脱转义字符。
String x = "hello\\nworld";
System.out.println("hello \\\\nworld");
Java具有与C中相同的转义序列String x = "hello\\\\nworld";
尝试使用\\\\n
这样的反斜杠
您可能想看看这种方法 。 尽管这样做可能会超出您的预期。 或者,对新行,回车符和制表符使用String替换方法。 请记住,还有诸如unicode和hex序列之类的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.