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?
A text block is an alternative form of Java string representation that can be used anywhere a traditional double quoted string literal can be used. For example: // Using a literal string String dqName = "Pat Q.
String result = str. trim(); The trim() method will remove both leading and trailing whitespace from a string and return the result.
Text blocks start with a “”” (three double-quote marks) followed by optional whitespaces and a newline. The most simple example looks like this: String example = """ Example text"""; Note that the result type of a text block is still a String.
The Java Text Blocks is a new feature of String literal. We can use Text Blocks to write multi-line strings in our programs, without bothering about any escape sequences or concatenations.
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 """;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With