可以将字符串转换为包含Java中的转义序列的字符串吗?

时间:2013-11-27 15:37:10

标签: java string file formatting escaping

说我输入一个字符串: -

Hello
Java!

我希望输出为: -

Hello\nJava!

有没有办法以这种格式获得输出?
我坚持这个,不能考虑任何可以为我做这个的逻辑。

2 个答案:

答案 0 :(得分:2)

http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringEscapeUtils.html看起来像你想要的那样。

EG

String escaped = StringEscapeUtils.escapeJava(String str)

将返回“Hello \ nJava!”当你提供你的字符串。

答案 1 :(得分:1)

嗯..您可以用\n替换换行符(\\n)。例如:

String helloWithNewLine = "Hello\nJava";
String helloWithoutNewLine = helloWithNewLine.replace("\n", "\\n");
System.out.println(helloWithoutNewLine);

输出:

Hello\nJava