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?
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
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