Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preserve trailing spaces in java 15 text blocks

Tags:

java

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?

like image 904
brass monkey Avatar asked Nov 03 '21 14:11

brass monkey


People also ask

What is Textblock in Java?

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.

How do you trim the spaces at the end of a string in Java?

String result = str. trim(); The trim() method will remove both leading and trailing whitespace from a string and return the result.

How do you block text in Java?

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.

Which of these is a function of Java text block?

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.


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
   """;
like image 170
brass monkey Avatar answered Oct 24 '22 21:10

brass monkey