Library contents

Java String.translateEscapes

Interpret Java escape sequences stored as literal characters in a string.

A simple example

String.translateEscapes

  1. Start with A, backslash, n, B
  2. Do this Interpret the escape
  3. Result A and B on two lines
The two written characters backslash and n become one newline.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println("A\\nB".translateEscapes());
    }
}
Output
A
B

Syntax

Java syntax
public String translateEscapes()
JDK 21 method signatures (1)
public String translateEscapes()
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Read two rows from a saved print template

A saved template contains escape markers that represent formatting instructions. Decode the stored markers once so the printed timetable has real tabs or line breaks at the intended positions.

From the programString saved = "Tea\\nRice"
Result2
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String saved = "Tea\\nRice";
        System.out.println(saved.translateEscapes().lines().count());
    }
}
Output
2

The literal backslash and n in the saved template become one line break.

Advertisements

Decode a tab marker in a timetable

A timetable template saves a marker between two columns rather than storing a real tab. Interpret the marker once so the renderer sees a column separator when preparing the final timetable.

From the programString saved = "09:00\\tMath"
Result09:00 | Math
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String saved = "09:00\\tMath";
        System.out.println(saved.translateEscapes().replace("\t", " | "));
    }
}
Output
09:00 | Math

The escape becomes a tab which the display replaces with a visible column divider.

Decode an address template

A mailroom stores the street and town in a one-line template. The stored template contains the two printable characters backslash and n. After decoding them as a newline, how many lines does the printer see?

GivenPier\nYork
Worked result2

What to watch for

This is Java escape syntax. Invalid escapes raise IllegalArgumentException and backslash-u Unicode escapes are not translated by this method.

Documentation for String.translateEscapes