Java String stripIndent() method

Java String stripIndent() method

String stripIndent() method added jdk 13.

This method is associated with text blocks, a preview feature of the Java language. Programs can only use this method when preview features are enabled. Preview features may be removed in a future release, or upgraded to permanent features of the Java language.

Returns a string whose value is this string, with incidental white space removed from the beginning and end of every line.
Incidental white space is often present in a text block to align the content with the opening delimiter. For example, in the following code, dots represent incidental white space:

 String html = """
 ..............<html>
 ..............    <body>
 ..............        <p>Hello, world</p>
 ..............    </body>
 ..............</html>
 ..............""";

This method treats the incidental white space as indentation to be stripped, producing a string that preserves the relative indentation of the content. Using | to visualize the start of each line of the string:
 |<html>
 |    <body>
 |        <p>Hello, world</p>
 |    </body>
 |</html>

First, the individual lines of this string are extracted as if by using lines().
Then, the minimum indentation (min) is determined as follows. For each non-blank line (as defined by isBlank()), the leading white space characters are counted. The leading white space characters on the last line are also counted even if blank. The min value is the smallest of these counts.

For each non-blank line, min leading white space characters are removed, and any trailing white space characters are removed. Blank lines are replaced with the empty string.

Finally, the lines are joined into a new string, using the LF character "\n" (U+000A) to separate lines.

API Note:
This method's primary purpose is to shift a block of lines as far as possible to the left, while preserving relative indentation. Lines that were indented the least will thus have no leading white space. The line count of the result will be the same as line count of this string. If this string ends with a line terminator then the result will end with a line terminator.
Implementation Note:
This method treats all white space characters as having equal width. As long as the indentation on every line is consistently composed of the same character sequences, then the result will be as described above.

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Hibernate Search - Elasticsearch with JSON manipulation

Spring Elasticsearch Operations