Baz
Baz

Reputation: 13135

Print escaped representation of a String

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

Upvotes: 5

Views: 7631

Answers (3)

jlordo
jlordo

Reputation: 37813

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

Upvotes: 9

Dunes
Dunes

Reputation: 40713

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

Upvotes: 3

Andreas Dolk
Andreas Dolk

Reputation: 114787

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)

Upvotes: 3

Related Questions