Search code examples
javastringescapingstring-formatting

How to display string formatters as plain text in Java?


I need to display escape sequences (like \n, \t) as literal text instead of having them interpreted as control characters. For example:

String text = "Hello\nWorld!"; System.out.println(text);

// Current output:
Hello
World!

// Desired output:
Hello\nWorld!

I've tried using replace():

String text = "Hello\nWorld!";
text = text.replace("\\", "\\\\");
text = text.replace("\n", "\\n");
System.out.println(text);

But this approach seems cumbersome, especially when dealing with multiple escape sequences and quotation marks. Is there a more elegant or built-in way to achieve this in Java?

Additional context:

  • The string may contain any escape sequence (\n, \t, \r, etc.)
  • The string might include single (') or double (") quotes
  • The solution should work with any valid Java string content

Solution

  • Here is an one way using streams.

    String text = "He\f\bllo\nWor\rld!";
    text = translate(text);
    

    prints

    He\f\bllo\nWor\rld!
    
    • this splits the string and then replaces the proper control character with its escaped outerpart.
    private static Map<Character, String> map = Map.of('\t', "\\t", '\b', "\\b", '\n',
            "\\n", '\f', "\\f", '\\', "\\\'", '"', "\\\"", '\r', "\\r");
    public static String translate(String text) {
        return text.chars()
                .mapToObj(ch -> map.getOrDefault((char)ch, Character.toString(ch)))
                .collect(Collectors.joining());    
    }