Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove only trailing spaces of a string in Java and keep leading spaces?

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?

like image 967
kzjfr0 Avatar asked Jun 07 '13 00:06

kzjfr0


People also ask

How do you remove trailing spaces from a string in Java?

To remove leading and trailing spaces in Java, use the trim() method. This method returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.

How can I remove the trailing spaces from a string?

String result = str.The trim() method will remove both leading and trailing whitespace from a string and return the result.

How do you remove leading and trailing characters from a string in Java?

In the StringUtils class, we have the methods stripStart() and stripEnd(). They remove leading and trailing characters respectively.

How do you remove leading and trailing spaces in Java 11?

Using String strip() APIs – Java 11 isWhitespace(char) method to determine a white space character. String strip() – returns a string whose value is given string, with all leading and trailing white space removed. Please note that String. trim() method also produces the same result.


1 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 

Online demo.

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

  • Java regular expression syntax
like image 149
Micha Wiedenmann Avatar answered Oct 23 '22 04:10

Micha Wiedenmann