In Java, stripTrailing() returns a string with all white space removed from the end, while the beginning and the middle stay exactly as they were. White space follows Character.isWhitespace.
It is the "right trim" counterpart to stripLeading(). Typical uses are padded columns from fixed-width files and lines that end with stray spaces or a line terminator.
stripTrailing() is an instance method of java.lang.String, added in Java 11. Call it on a string, as in text.stripTrailing(); calling it on a null reference throws NullPointerException. Strings are immutable, so it never changes the original: it returns a new String (or the same one when nothing changes). Keep the result. Requires Java 11 or newer.
Syntax
Call it with no arguments.
java
String name = row.stripTrailing();
String line = rawLine.stripTrailing(); // also drops \r\n at the end
Call
What it does
" a ".stripTrailing()
" a".
"end\r\n".stripTrailing()
"end".
"x".stripTrailing()
"x", the same object.
Line terminators are white space too, so stripTrailing() removes a final \n or \r\n along with any spaces before it. Leading indentation is preserved, which matters for code and poetry.
Library declarations
java
public String stripTrailing();
Parameters
Parameter
Description
None
stripTrailing() takes no parameters.
Return Value
Return Value
Description
String
The text without trailing white space, or this string if it has none.
Java Examples
Example 1 — Strip Only the Right Side
The same padded text as before, cleaned from the other end.
java
public class StripTrailingBasic {
public static void main(String[] args) {
String s = " left and right ";
System.out.println("[" + s.stripTrailing() + "]");
System.out.println(s.length() + " -> " + s.stripTrailing().length());
}
}
Output
[ left and right]
20 -> 17
How It Works
The end is cleaned. The closing bracket now sits right after right.
The start is preserved. The three leading spaces are still there, so indentation survives.
Three chars fewer. The length drops from 20 to 17, exactly the trailing spaces.
Example 2 — Read Names from Fixed-Width Rows
Each record pads its name with spaces to ten characters.
java
public class StripTrailingRows {
public static void main(String[] args) {
String[] rows = {"Ada ", "Grace ", "Linus "};
for (String row : rows) {
String name = row.stripTrailing();
System.out.println(name + " (" + name.length() + ")");
}
}
}
Output
Ada (3)
Grace (5)
Linus (5)
How It Works
Padded columns. Every row is 10 chars wide, with spaces filling the space after the name.
Drop the padding.stripTrailing() removes those spaces, leaving only the name.
Real lengths. The printed lengths 3, 5, and 5 confirm that no padding remains.
Example 3 — Remove a Line Ending but Keep Inner Spaces
Clean a line read with its Windows line terminator.