如何用Java将换行符替换为“ \ n”?

时间:2019-04-30 13:32:07

标签: java replace newline

我想用“ \ n”替换换行符,但是我的代码无法正常工作。

 <table>
      <tr>
        <th>Max value</th>
      </tr>
      <tr *ngIf="data[0].reportItems | max: 'savingPotentialPercent' as result">
        <td>{{ result }}</td>

      </tr>
    </table>

预期:“ Hello \ n World”

实际:

“你好

世界”

5 个答案:

答案 0 :(得分:3)

尝试一下。

class Scratch {
    public static void main(String[] args) {
        System.out.println("Hello\n world".replace("\n", "\\n"));
    }
}

答案 1 :(得分:1)

如果要显示反斜杠,则必须转义它。否则它将被解释为新行。

str = str.replaceAll("\n","\\\\n"));

答案 2 :(得分:0)

'\ n'表示新行,例如'\ t'是制表符,'\'是转义字符,表示其后的字符不被视为普通文本(您应阅读有关转义字符的内容)更多详细信息),因此,如果要实际键入“ \”,则需要用“ \”表示它,这意味着如果要具有“ \ n”,则应键入“ \ n”。请检查转义字符,不要只是在不理解的情况下使用此信息。

答案 3 :(得分:0)

您可以使用以下3种方法来使您的代码正常运行:

#1
text = str.replace("\n", "\\n");

#2
text = str.replace(System.getProperty("line.separator"), "\\n");

#3
text = text.replaceAll("\\n", "\\\\n");

答案 4 :(得分:0)

您可以使用以下代码来实现

String hello = "hello\nworld";
hello=hello.replaceAll("\\n", "\\\\n");
System.out.println(hello);
相关问题