Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print raw string in java [duplicate]

Tags:

java

Say I have a string like this:

String message = "Hi \n Prakash";

I want to print messsage exactly the way it is rather than printing a newline for \n. So the desired output is:

Hi \n Prakash

and not

Hi
 Prakash

Please note that we are not allowed to modify the string message. How do I do this?

Edit: I've used \n just as an example. There could be similar characters like \t which could possibly be in my string.

like image 231
prakasht Avatar asked Oct 26 '25 12:10

prakasht


1 Answers

This can be done with the help of StringEscapeUtils class from Apache Commons Text.

import org.apache.commons.lang3.StringEscapeUtils;
String message = "Hi \n Prakash";
System.out.println(StringEscapeUtils.escapeJava(message));

The output is:

Hi \n Prakash

Thanks Dima for providing the link in answer.

like image 79
prakasht Avatar answered Oct 28 '25 03:10

prakasht



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!