5

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
Baz
  • 12,713
  • 38
  • 145
  • 268
  • 2
    The internal representation has a tab character. It doesn't have a backslash and a t. What *exactly* are you trying to do? – Jon Skeet Dec 04 '12 at 11:18
  • @Jon Skeet Say I get a string from somewhere. I want to know exactly what it contains. I want to see "String:\tA" rather than "String: A" – Baz Dec 04 '12 at 11:26
  • 1
    @Baz: Sure. But I just want to make sure that you understand that "\t" is just the Java source code representation. Your question talks about the "internal representation" - it's just a tab character. – Jon Skeet Dec 04 '12 at 11:28
  • Duplicate of http://stackoverflow.com/q/7888004/873282 – koppor Dec 22 '15 at 11:26
  • Does this answer your question? [How do I print escape characters in Java?](https://stackoverflow.com/questions/7888004/how-do-i-print-escape-characters-in-java) – M. Justin Sep 14 '21 at 15:25

3 Answers3

9

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

howlger
  • 31,050
  • 11
  • 59
  • 99
jlordo
  • 37,490
  • 6
  • 58
  • 83
  • This is an old Q&A but its very useful especially for test generation. The updated link is https://commons.apache.org/proper/commons-lang/ and the package is now commons.lang3.... , that is use: org.apache.commons.lang3.StringEscapeUtils.escapeJava(yourString); – ArtisanV Jul 14 '16 at 18:24
3

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)

Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
3

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
Dunes
  • 37,291
  • 7
  • 81
  • 97
  • 1
    Fixed the link. For future reference, googling "StringEscapeUtils apache" will easily find the documentation. – Dunes Jul 14 '15 at 10:58