Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly trim whitespaces from a string in Java?

The JDK's String.trim() method is pretty naive, and only removes ascii control characters.

Apache Commons' StringUtils.strip() is slightly better, but uses the JDK's Character.isWhitespace(), which doesn't recognize non-breaking space as whitespace.

So what would be the most complete, Unicode-compatible, safe and proper way to trim a string in Java?

And incidentally, is there a better library than commons-lang that I should be using for this sort of stuff?

like image 476
itsadok Avatar asked Sep 17 '09 10:09

itsadok


People also ask

How do I remove whitespaces from a string?

Use the String. replace() method to remove all whitespace from a string, e.g. str. replace(/\s/g, '') . The replace() method will remove all whitespace characters by replacing them with an empty string.

How do you trim a character in a string in Java?

The trim() method in Java String is a built-in function that eliminates leading and trailing spaces. The Unicode value of space character is '\u0020'. The trim() method in java checks this Unicode value before and after the string, if it exists then removes the spaces and returns the omitted string.

How do you remove extra 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.


1 Answers

Google has made guava-libraries available recently. It may have what you are looking for:

CharMatcher.inRange('\0', ' ').trimFrom(str) 

is equivalent to String.trim(), but you can customize what to trim, refer to the JavaDoc.

For instance, it has its own definition of WHITESPACE which differs from the JDK and is defined according to the latest Unicode standard, so what you need can be written as:

CharMatcher.WHITESPACE.trimFrom(str) 
like image 75
CrazyCoder Avatar answered Sep 28 '22 19:09

CrazyCoder