Java String stripIndent Example

1. Introduction

This blog post discusses the stripIndent() method in Java's String class. Introduced in Java 15 as part of JEP 368: Text Blocks (Second Preview), stripIndent() is a method that helps to remove incidental white space from multi-line strings, making them cleaner and more consistent.

Definition

String.stripIndent() is a method that adjusts the indentation of each line of a multi-line string based on the minimum indentation of all lines. It removes the same amount of leading white space from each line, ensuring consistent indentation across the entire string.

2. Program Steps

1. Create a multi-line string using text blocks.

2. Use the stripIndent() method to adjust the indentation.

3. Display the result of the operation.

3. Code Program

public class StringStripIndentExample {
    public static void main(String[] args) {
        String textBlock = """
                Line 1
                Line 2
                    Line 3
                Line 4""";

        // Adjusting indentation using stripIndent()
        String result = textBlock.stripIndent();

        // Displaying the result
        System.out.println(result);
    }
}

Output:

Line 1
Line 2
    Line 3
Line 4

Explanation:

1. textBlock is a multi-line string defined using Java's text block syntax, which includes incidental indentation.

2. The stripIndent() method is called on textBlock. This method calculates the common minimum indentation from all lines and strips it.

3. The result is a string where the incidental indentation from the text block syntax is removed, aligning all lines to the left margin while preserving the relative indentation.

4. The output shows the adjusted string, demonstrating how stripIndent() effectively normalizes the indentation of multi-line strings, especially useful in scenarios involving text blocks.


Comments