jabalsad
jabalsad

Reputation: 2421

How do I print escape characters in Java?

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.

Upvotes: 27

Views: 63566

Answers (9)

Christopher Yeleighton
Christopher Yeleighton

Reputation: 454

The following code produces octal escape sequences. Modify the replacement function to produce what you need.

Pattern
 .compile ("[^\\p{Graph}]")
 .matcher ("A\tB\nC")
 .replaceAll
 (
   (final MatchResult r)
   -> String .format ("\\\\%03o", + r .group () .charAt (0)))

Another possibility would be to use String .format ("^%c", r .group () .charAt (0) + '@')—but it will only handle control characters.

Upvotes: 0

JudeFeng
JudeFeng

Reputation: 398

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

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

Upvotes: 39

G_H
G_H

Reputation: 12019

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.

Upvotes: -1

Vlad
Vlad

Reputation: 18633

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

Upvotes: 17

pgras
pgras

Reputation: 12780

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

Upvotes: 2

FailedDev
FailedDev

Reputation: 26940

Try to escape the backslash like \\n

Upvotes: 1

BastiS
BastiS

Reputation: 452

Just escape the escape character.

String x = "hello\\nworld";

Upvotes: 1

starrify
starrify

Reputation: 14781

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

Upvotes: 1

Francisco Paulo
Francisco Paulo

Reputation: 6322

You have to escape the slash itself:

String x = "hello\\nworld";

Upvotes: 2

Related Questions