Library contents

Java String.stripLeading

Remove whitespace only at the beginning of the input.

A simple example

String.stripLeading

  1. Start with " A "
  2. Do this Remove leading spaces
  3. Result A then two spaces
Only the spaces before A disappear.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println("[" + "  A  ".stripLeading() + "]");
    }
}
Output
[A  ]

Syntax

Java 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.java

Align 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.

From the programString address = " North Road"
ResultNorth Road
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String address = "   North Road";
        System.out.println(address.stripLeading());
    }
}
Output
North Road

The first visible character moves to the beginning of the string.

Advertisements

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.

From the programString badge = " Ada "
Result[Ada ]
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String badge = "  Ada ";
        System.out.println("[" + badge.stripLeading() + "]");
    }
}
Output
[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.

Given' Art '
Worked result[Art ]

What to watch for

Use stripTrailing for the opposite edge. Keep whitespace when indentation carries meaning.

Documentation for String.stripLeading