The trim()
function removes both the trailing and leading space, however, if I only want to remove the trailing space of a string, how can I do it?
10 Answers
Since JDK 11
If you are on JDK 11 or higher you should probably be using stripTrailing().
Earlier JDK versions
Using the regular expression \s++$
, you can replace all trailing space characters (includes space and tab characters) with the empty string (""
).
final String text = " foo ";
System.out.println(text.replaceFirst("\\s++$", ""));
Output
foo
Here's a breakdown of the regex:
\s
– any whitespace character,++
– match one or more of the previous token (possessively); i.e., match one or more whitespace character. The+
pattern is used in its possessive form++
, which takes less time to detect the case when the pattern does not match.$
– the end of the string.
Thus, the regular expression will match as much whitespace as it can that is followed directly by the end of the string: in other words, the trailing whitespace.
The investment into learning regular expressions will become more valuable, if you need to extend your requirements later on.
References

- 19,979
- 21
- 92
- 137
-
9@WChargin Thank you for providing the breakdown of the regular expression. I think more people should follow your lead and improve answers. – Micha Wiedenmann Jun 07 '13 at 01:10
Another option is to use Apache Commons StringUtils
, specifically StringUtils.stripEnd
String stripped = StringUtils.stripEnd(" my lousy string "," ");

- 20,112
- 2
- 49
- 58
-
1
-
2I agree. However, you should make it a point to tag your questions with `android` as `android` is not `Java`. – Tim Bender Jun 07 '13 at 04:59
-
1@TimBender This is my fault, I removed the android tag, since the question seemed generic Java to me. I am sorry. – Micha Wiedenmann Jun 07 '13 at 09:07
-
5Android can use this with no doubt. You should import org.apache.commons.lang3 not org.apache.commons.lang. It works on API 19+. – Kimi Chiu Apr 26 '16 at 03:30
I modified the original java.lang.String.trim()
method a bit and it should work:
public String trim(String str) {
int len = str.length();
int st = 0;
char[] val = str.toCharArray();
while ((st < len) && (val[len - 1] <= ' ')) {
len--;
}
return str.substring(st, len);
}
Test:
Test test = new Test();
String sample = " Hello World "; // A String with trailing and leading spaces
System.out.println(test.trim(sample) + " // No trailing spaces left");
Output:
Hello World // No trailing spaces left

- 69,608
- 17
- 111
- 137
As of JDK11
you can use stripTrailing:
String result = str.stripTrailing();

- 54,915
- 8
- 91
- 126
The most practical answer is @Micha's, Ahmad's is reverse of what you wanted so but here's what I came up with in case you'd prefer not to use unfamiliar tools or to see a concrete approach.
public String trimEnd( String myString ) {
for ( int i = myString.length() - 1; i >= 0; --i ) {
if ( myString.charAt(i) == ' ' ) {
continue;
} else {
myString = myString.substring( 0, ( i + 1 ) );
break;
}
}
return myString;
}
Used like:
public static void main( String[] args ) {
String s = " Some text here ";
System.out.println( s + "|" );
s = trimEnd( s );
System.out.println( s + "|" );
}
Output:
Some text here | Some text here|

- 13,548
- 8
- 49
- 75
-
1
-
2@WChargin: Student. We are allowed to use C++, C#, and/or Java, but no utilities or anything that makes your life easy. I'm going to update it to be more general. – ChiefTwoPencils Jun 07 '13 at 01:21
The best way in my opinion:
public static String trimEnd(String source) {
int pos = source.length() - 1;
while ((pos >= 0) && Character.isWhitespace(source.charAt(pos))) {
pos--;
}
pos++;
return (pos < source.length()) ? source.substring(0, pos) : source;
}
This does not allocate any temporary object to do the job and is faster than using a regular expression. Also it removes all whitespaces, not just ' '.

- 12,779
- 3
- 59
- 51
Here's a very short, efficient and easy-to-read version:
public static String trimTrailing(String str) {
if (str != null) {
for (int i = str.length() - 1; i >= 0; --i) {
if (str.charAt(i) != ' ') {
return str.substring(0, i + 1);
}
}
}
return str;
}
As an alternative to str.charAt(i) != ' '
you can also use !Character.isWhitespace(str.charAt(i)
if you want to use a broader definition of whitespace.

- 18,404
- 12
- 87
- 115
This code is intended to be read a easily as possible by using descriptive names (and avoiding regular expressions).
It does use Java 8's Optional
so is not appropriate for everyone.
public static String removeTrailingWhitspace(String string) {
while (hasWhitespaceLastCharacter(string)) {
string = removeLastCharacter(string);
}
return string;
}
private static boolean hasWhitespaceLastCharacter(String string) {
return getLastCharacter(string)
.map(Character::isWhitespace)
.orElse(false);
}
private static Optional<Character> getLastCharacter(String string) {
if (string.isEmpty()) {
return Optional.empty();
}
return Optional.of(string.charAt(string.length() - 1));
}
private static String removeLastCharacter(String string) {
if (string.isEmpty()) {
throw new IllegalArgumentException("String must not be empty");
}
return string.substring(0, string.length() - 1);
}
String value= "Welcome to java ";
So we can use
value = value.trim();

- 7
-
2
-
trim() Returns a copy of the string, with both leading and trailing whitespace omitted. – rumman0786 Aug 21 '20 at 08:15