Java: How do I print \\n in output?

时间:2017-12-18 06:49:51

标签: java string replace

I have wanted to print \n in output by replacing \r\n:

I have written my code as such : "John \r\n find".replaceAll("\r\n", "\\\\n"));

But the output comes as such always:

John \n find

I wanted the output to be : John \\n find

1 个答案:

答案 0 :(得分:0)

A platform-independent way of replacing the String \r\n with a new line separator would be:

String s = "John \r\n find".replaceAll("\r\n", System.getProperty("line.separator"));
System.out.println(s);

Output is (note that the blanks are kept, of course):

John
 find

In order to replace the blank characters as well use:

"John \r\n find".replaceAll(" \r\n ", System.getProperty("line.separator"));