How to properly trim whitespaces from a string in Java?

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)

Leave a Comment