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