我有类似的字符串"hello\nworld"
,如果我使用
System.out.println(string);
它会像这样:
你好
世界
或者如果我使用
System.out.printf(string);
它会输出:helloworld
,但我想要输出完全一样的java方法:hello\nworld
意味着我想忽略像换行符这样的反斜杠字符。
我有类似的字符串"hello\nworld"
,如果我使用
System.out.println(string);
它会像这样:
你好
世界
或者如果我使用
System.out.printf(string);
它会输出:helloworld
,但我想要输出完全一样的java方法:hello\nworld
意味着我想忽略像换行符这样的反斜杠字符。
然后你需要将你的 String 构造为
String s = "hello\\nworld";
逃避反斜杠。
使用 apache commons StringEscapeUtils。
System.out.println("String s = \""
+ StringEscapeUtils.escapeJava(string)
+ "\";");
然后将制表符"\t"
替换为反斜杠和t
. 正如其他人所说,字符串表示表示一些特殊字符,如换行符/换行符和\n
.
以上将适合生成Java源代码左右。
只需将您的字符串更改为String s = "hello\\nworld";
你也可以参考这里:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
\
是字符串中的特殊字符。它可用于:
\n
)、CR(回车符 -> \r
)、制表符 ->\t
"
,您需要先转义它\"
,在您的情况下,要能够打印\
,您需要使用其他反斜杠(如"\\"
.