问题
Cannot find a solution to seem to be a simple question. For example, I have a string with LineBreak ”a\na”. The System.out.println output of this string shows 2 lines. However, I need to show the output in exactly the same form, i.e. “a\na”. How to achieve this?
回答1:
You need to escape your \n
with an extra backslash..
Use: - "a\\na"
to get \n
in your output..
System.out.println("a\\na"); // Prints a\na
Or, you can also take a look at :- Apache Commons StringEscapeUtils#escapeJava which will automatically excape all the special escape sequences
with an extra backslash..
String str = "a\nb\r\t";
String result = StringEscapeUtils.escapeJava(str); // Takes `\n` as `\\n`
System.out.println(result);
This will print: - a\nb\r\t
回答2:
For a general purpose solution you could look at something like StringEscapeUtils.escapeJava from Apache Commons
来源:https://stackoverflow.com/questions/12882219/how-to-show-special-escape-characters-like-linebreak-in-java-output