I wish to print out strings to the console and it is important to see the exact string meaning that it should show the newline character \n
in the logs. So it will be "this is the exact sequence of chars \n"
Asked
Active
Viewed 5,151 times
3

Alex Bollbach
- 4,370
- 9
- 32
- 80
1 Answers
3
You could replace all occurrences of the \n
character with \\n
(which will appear as \n
when printed). You should also replace occurrences of the \r
character with \\r
in case it is present.
String str = "this is the exact sequence of chars \n";
str = str.replace("\n", "\\n");
str = str.replace("\r", "\\r");
System.out.println(str);

Francesco Amodeo
- 3
- 1

SamTebbs33
- 5,507
- 3
- 22
- 44
-
1Why `String.valueOf('\n')`, rather than simply `"\n"`? – Andy Turner Jun 23 '16 at 21:04