Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

139
Views
How to preserve trailing spaces in java 15 text blocks

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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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
   """;
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!