Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I print escape characters in Java?

Tags:

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 

I would like to see the actual escape characters for debugging purposes.

like image 478
jabalsad Avatar asked Oct 25 '11 10:10

jabalsad


People also ask

How do I print an escape character?

We have many escape characters in Python like \n, \t, \r, etc., What if we want to print a string which contains these escape characters? We have to print the string using repr() inbuilt function. It prints the string precisely what we give.


2 Answers

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

String x = "hello\nworld"; System.out.print(StringEscapeUtils.escapeJava(x)); 
like image 93
JudeFeng Avatar answered Oct 04 '22 10:10

JudeFeng


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)).

like image 35
Vlad Avatar answered Oct 04 '22 11:10

Vlad