【问题标题】:Can a string be converted to a string containing escape sequences in Java?Java中的字符串可以转换为包含转义序列的字符串吗?
【发布时间】:2013-11-27 15:37:10
【问题描述】:

假设我输入了一个字符串:-

Hello
Java!

我希望输出为:-

Hello\nJava!

有什么方法可以得到这种格式的输出?
我被困在这个问题上,无法思考任何可以为我做到这一点的逻辑。

【问题讨论】:

  • 在哪里输入字符串?在构建字符串时,您必须附加 "\n"
  • 是的!你是对的。即使我使用 Scanner 类,它也只需要一行。所以我该怎么做?有什么建议么?使用文件或其他东西。我对此感到非常困惑。

标签: java string file formatting escaping


【解决方案1】:

看起来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!”与您的字符串一起提供时。

【讨论】:

    【解决方案2】:

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

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

    输出:

    Hello\nJava
    

    【讨论】:

    • 先生,这不是我的问题。
    猜你喜欢
    • 2012-02-02
    • 2019-09-19
    • 1970-01-01
    • 1970-01-01
    • 2013-01-29
    • 1970-01-01
    • 2021-07-07
    • 2017-09-06
    • 2018-09-24
    相关资源
    最近更新 更多