How to preserve trailing spaces in java 15 text blocks

Viewed 369

When defining a String using text blocks by default the trailing white space gets removed as it's treated as incidental white space.

var text = """
    blah blah       
    blah        
    """;

How can I preserve trailing spaces in a text block so that each line in the block end on the same length?

1 Answers

This can be done using an escape sequence for space at the end of a line. E.g.

var text = """
    blah blah    \s       
    blah         \s
    """;

See https://docs.oracle.com/en/java/javase/15/text-blocks/index.html#new-escape-sequences

The \s escape sequence simple translates to space (\040, ASCII character 32, white space.) Since escape sequences don't get translated until after incident space stripping, \s can act as fence to prevent the stripping of trailing white space. Using \s at the end of each line in the following example, guarantees that each line is exactly six characters long.

String colors = """
   red  \s
   green\s
   blue \s
   """;
Related