Java String.stripLeading
Remove whitespace only at the beginning of the input.
A simple example
String.stripLeading
- Start with " A "
- Do this Remove leading spaces
- Result A then two spaces
class Main {
public static void main(String[] args) throws Exception {
System.out.println("[" + " A ".stripLeading() + "]");
}
}
[A ]
Syntax
public String stripLeading()
JDK 21 method signatures (1)
public String stripLeading()Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaAlign a pasted delivery address
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 address = " North Road";
System.out.println(address.stripLeading());
}
}
North Road
The first visible character moves to the beginning of the string.
Retain a reserved space after a badge name
A badge template reserves a space after its name field for later printing. Remove or preserve whitespace on the intended side only so that reserved position survives the cleanup.
class Main {
public static void main(String[] args) throws Exception {
String badge = " Ada ";
System.out.println("[" + badge.stripLeading() + "]");
}
}
[Ada ]
Only the left padding disappears. The bracket makes the trailing space visible.
Clean a course import
A course name arrives padded on both sides. Remove only the leading spaces. Brackets make any spaces left at the end visible.
What to watch for
Use stripTrailing for the opposite edge. Keep whitespace when indentation carries meaning.