stripLeading() and stripTrailing(): Directional Stripping
You'll learn how to remove whitespace from just the beginning or just the end of a string using Java 11's directional strip methods.
The Concept: Surgical Whitespace Removal
While strip() removes whitespace from both ends of a string (and trim() does similar with a narrower definition of whitespace), sometimes you need finer control. Java 11 introduced stripLeading() and stripTrailing() to remove whitespace from only one side at a time.
Think of it like trimming a hedge: sometimes you only need to trim the left side or the right side, not both.
How They Work
stripLeading() removes all Unicode whitespace characters from the beginning (left side) of the string, leaving the end untouched.
stripTrailing() removes all Unicode whitespace characters from the end (right side) of the string, leaving the beginning untouched.
String text = " Hello World! ";
String noLeading = text.stripLeading();
// Result: "Hello World! " (spaces at end preserved)
String noTrailing = text.stripTrailing();
// Result: " Hello World!" (spaces at start preserved)
String neither = text.strip();
// Result: "Hello World!" (both sides removed)
Use Cases
These methods shine when formatting output where you need precise control over spacing, or when processing text where leading or trailing whitespace has different semantic meaning:
String indentedCode = " int x = 5;";
String normalized = indentedCode.stripLeading();
// "int x = 5;" - removes indentation but keeps code intact
Key Takeaway: Use stripLeading() to remove whitespace from only the start of a string and stripTrailing() to remove it from only the end, giving you directional control over whitespace removal.