Library contents

Java String.stripTrailing

Remove trailing Java whitespace while keeping the leading indentation.

A simple example

String.stripTrailing

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

Syntax

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

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

java Main.java

Clean the end of a shelf label

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 shelf = "A-12 "
ResultA-12
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String shelf = "A-12  ";
        System.out.println(shelf.stripTrailing());
    }
}
Output
A-12

The last visible digit becomes the final character.

Advertisements

Preserve indentation in a schedule

A copied checklist or timetable contains meaningful indentation. Adjust the requested leading margin and preserve the subordinate levels so the printed layout still communicates its structure.

From the programString line = " 09:00 "
Result[ 09:00]
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String line = "  09:00  ";
        System.out.println("[" + line.stripTrailing() + "]");
    }
}
Output
[  09:00]

The opening bracket shows that the leading two spaces remain.

Clean a course import

A course name arrives padded on both sides. Remove only the trailing spaces. Brackets show any indentation left at the front.

Given' Art '
Worked result[ Art]

What to watch for

This operates on the end of the whole string, rather than trimming every line independently.

Documentation for String.stripTrailing