Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print escaped representation of a String

Tags:

java

How do I print the escaped representation of a string, for example if I have:

s = "String:\tA"

I wish to output:

String:\tA

on the screen instead of

String:    A
like image 428
Baz Avatar asked Dec 04 '12 11:12

Baz


3 Answers

I think you are looking for:

String xy = org.apache.commons.lang.StringEscapeUtils.escapeJava(yourString);
System.out.println(xy);

from Apache Commons Lang v2.6

deprecated in Apache Commons Lang v3.5+, use Apache Commons Text v1.2

like image 189
jlordo Avatar answered Sep 27 '22 22:09

jlordo


Well strictly speaking the internal representation is an unsigned 16-bit integer. I think what you mean is that you want to escape the string.

There's a class called StringEscapeUtils in the Apache library to help with that.

String escaped = StringEscapeUtils.escapeJava("\t");
System.out.println(escaped); // prints \t
like image 25
Dunes Avatar answered Sep 27 '22 22:09

Dunes


For a given String you'll have to replace the control characters (like tab):

System.out.println("String:\tA\n".replace("\t", "\\t").replace("\n","\\n");

(and for the others too)

like image 33
Andreas Dolk Avatar answered Sep 27 '22 21:09

Andreas Dolk