17

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 Answer 1

24

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
   """;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.