Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Print strings showing newline characters [duplicate]

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"

like image 208
Alex Bollbach Avatar asked May 18 '26 01:05

Alex Bollbach


1 Answers

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);
like image 138
SamTebbs33 Avatar answered May 20 '26 14:05

SamTebbs33



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!