Java String.stripIndent
Remove common incidental indentation from a multiline string while preserving relative indentation.
A simple example
String.stripIndent
- Start with Two spaces then A, two spaces then B
- Do this Remove common leading indent
- Result Lines A and B
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.javaAlign 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.
class Main {
public static void main(String[] args) throws Exception {
String checklist = " Pack\n Label";
System.out.println(checklist.stripIndent().replace("\n", " / "));
}
}
Pack / Label
Four shared spaces disappear. Label retains its extra two spaces.
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.
class Main {
public static void main(String[] args) throws Exception {
String notice = " Gate A \n Gate B ";
System.out.println(notice.stripIndent().replace("\n", "|"));
}
}
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?
What to watch for
A final line terminator influences the common indentation. This example supplies strings without a trailing newline.