Question

I have string like "hello\nworld" and if i use

System.out.println(string);

it will out put like:

hello
world

Or if i use

System.out.printf(string);

it will out put: helloworld
but i want java method that output exactly like it:hello\nworld
means i want ignore backslash character like newline.

Was it helpful?

Solution 2

Use apache commons StringEscapeUtils.

System.out.println("String s = \""
    + StringEscapeUtils.escapeJava(string)
    + "\";");

A tab character "\t" is then replaced with a backslash and a t. As others said, the String representations represents some special characters like linefeed/newline with \n.

The above would be fit for generating Java source code or so.

OTHER TIPS

Then you need to construct your String as

String s = "hello\\nworld";

to escape the backslash.

Just change your string to String s = "hello\\nworld";

You can also refer here:

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

\ is special character in String. It can be used to:

  • create special characters that normally can't be written like LF (line fead -> \n), CR (Carriage return -> \r), tabulator -> \t
  • escape other characters that have special meaning in String, for instance to print " you need to escape it first \" and in your case to be able to print \ you need to escape it with other backslash like "\\".
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top