How do I print escape characters in Java

匿名 (未验证) 提交于 2019-12-03 02:11:02

问题:

When I have a string such as:

String x = "hello\nworld"; 

How do I get Java to print the actual escape character (and not interpret it as an escape character) when using System.out?

For example, when calling

System.out.print(x); 

I would like to see:

hello\nworld 

And not:

hello world 

EDIT: My apologies, I should clarify the question. I have no control over what 'x' is going to be, it may be a string I read from a file. I would like for x to retain its escape characters during normal program execution, but for debugging purposes I would like to see the actual escape characters.

Writing a method that subs each and every escape character seems overkill. Isn't there a better printing library other than PrintStream that does this for me?

If you're familiar with Ruby, think x.inspect()

回答1:

One way to do this is:

public static String unEscapeString(String s){     StringBuilder sb = new StringBuilder();     for (int i=0; i<s.length(); i++)         switch (s.charAt(i)){             case '\n': sb.append("\\n"); break;             case '\t': sb.append("\\t"); break;             // ... rest of escape characters             default: sb.append(s.charAt(i));         }     return sb.toString(); } 

and you run System.out.print(unEscapeString(x)).



回答2:

Use the method "StringEscapeUtils.escapeJava" in Java lib "org.apache.commons.lang"

String x = "hello\nworld"; System.out.print(StringEscapeUtils.escapeJava(x)); 


回答3:

You have to escape the slash itself:

String x = "hello\\nworld"; 


回答4:

Just escape the escape character.

String x = "hello\\nworld"; 


回答5:

System.out.println("hello \\nworld");



回答6:

Java has its escape-sequence just the same as that in C. use String x = "hello\\nworld";



回答7:

Try to escape the backslash like \\n



回答8:

You might want to check out this method. Although this may do more than you intend. Alternatively, use String replace methods for new lines, carriage returns and tab characters. Do keep in mind that there are also such things as unicode and hex sequences.



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