How to show special escape characters like LineBreak in Java output?

久未见 提交于 2019-12-23 20:28:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!