Java String.stripTrailing
Remove trailing Java whitespace while keeping the leading indentation.
A simple example
String.stripTrailing
- Start with " A "
- Do this Remove trailing spaces
- Result Two spaces then A
class Main {
public static void main(String[] args) throws Exception {
System.out.println("[" + " A ".stripTrailing() + "]");
}
}
[ A]
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.javaClean 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.
class Main {
public static void main(String[] args) throws Exception {
String shelf = "A-12 ";
System.out.println(shelf.stripTrailing());
}
}
A-12
The last visible digit becomes the final character.
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.
class Main {
public static void main(String[] args) throws Exception {
String line = " 09:00 ";
System.out.println("[" + line.stripTrailing() + "]");
}
}
[ 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.
What to watch for
This operates on the end of the whole string, rather than trimming every line independently.