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:
\n
, \t
, \r
, etc.)'
) or double ("
) quotesHere is an one way using streams.
String text = "He\f\bllo\nWor\rld!";
text = translate(text);
prints
He\f\bllo\nWor\rld!
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());
}