Library contents

Java String.stripIndent

Remove common incidental indentation from a multiline string while preserving relative indentation.

A simple example

String.stripIndent

  1. Start with Two spaces then A, two spaces then B
  2. Do this Remove common leading indent
  3. Result Lines A and B
With no final blank line, both lines contribute two spaces to the common indent.

Syntax

Java syntax
public String stripIndent()
JDK 21 method signatures (1)
public String stripIndent()
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Align a copied two-level checklist

A user pastes a multi-line block from a formatted document into a plain-text field. Remove the common outer margin while preserving meaningful differences between the lines inside it.

From the programString checklist = " Pack\n Label"
ResultPack / Label
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String checklist = "    Pack\n      Label";
        System.out.println(checklist.stripIndent().replace("\n", " / "));
    }
}
Output
Pack /   Label

Four shared spaces disappear. Label retains its extra two spaces.

Advertisements

Remove trailing whitespace from a notice

A terminal appends padding or a line ending to the final field it exports. Remove the trailing characters before comparing or displaying the value, while retaining the beginning of the field.

From the programString notice = " Gate A \n Gate B "
ResultGate A|Gate B
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String notice = "  Gate A   \n  Gate B ";
        System.out.println(notice.stripIndent().replace("\n", "|"));
    }
}
Output
Gate A|Gate B

Both rows lose their shared margin and their trailing spaces.

Align an exhibit checklist

A curator pastes two indented lines from a planning document. The sample has the same two-space indentation on every nonempty line. Which first word appears when removing that common indentation?

Given“ Mount” / “ Light”
Worked resultMount

What to watch for

A final line terminator influences the common indentation. This example supplies strings without a trailing newline.

Documentation for String.stripIndent