Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raw String Literals - Remove Leading Indentation

Edit: Raw String Literals have been dropped from JDK 12, but I'm going to leave this question open and will edit it accordingly whenever Raw String Literals are reintroduced.


When testing Raw String Literals (which are a preview feature in Java 12), I came across the following snippet of code:

System.out.println(`
        Test 1
            Test 2
                Test 3
`);

Which outputs the following:

          
        Test 1
            Test 2
                Test 3
                          

However, I want the output to resemble the following:

Test 1
    Test 2
        Test 3

What is the easiest way to remove the leading indentation to match the intended format?

like image 620
Jacob G. Avatar asked Nov 18 '18 02:11

Jacob G.


1 Answers

Accompanying Raw String Literals as a preview feature in Java 12 are new methods that will be added to java.lang.String, one of which is String#align. Its documentation states the following:

Removes vertical and horizontal white space margins from around the essential body of a multi-line string, while preserving relative indentation.

...

For each non-blank line, min leading white space characters are removed. Each white space character is treated as a single character. In particular, the tab character "\t" (U+0009) is considered a single character; it is not expanded.

Leading and trailing blank lines, if any, are removed. Trailing spaces are preserved.

Each line is suffixed with a line feed character "\n" (U+000A).

To use this method, we can change the code to the following:

System.out.println(`
    Test 1
        Test 2
            Test 3
`.align());

Which outputs the following (suffixed with a line feed character, as stated by the documentation):

Test 1
    Test 2
        Test 3
like image 100
Jacob G. Avatar answered Oct 31 '22 16:10

Jacob G.