What is a good alternative of JavaScript ltrim()
and rtrim()
functions in Java?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
With a regex you could write:
If you have to do it often, you can create and compile a pattern for better performance:
From a performance perspective, a quick micro benchmark shows (post JIT compilation) that the regex approach is about 5 times slower than the loop (0.49s vs. 0.11s for 1 million ltrim).
I personally find the regex approach more readable and less error prone but if performance is an issue you should use the loop solution.
Using regex may be nice, but it's quite a lot slower than a simple trimming functions:
Source: http://www.fromdev.com/2009/07/playing-with-java-string-trim-basics.html
Also, there are some libraries providing such functions. For example, Spring StringUtils. Apache Commons StringUtils provides similar functions too: strip, stripStart, stripEnd
Based on the answer of @bezmax I had a look at the Spring
StringUtils
, but it couldn't justify the overload for me of switching to the Spring framework. Therfore I decided to create aCharacters
class to easily left / right trim strings for any given character(-class). The class is available on GitHub.If you would like to trim for whitespaces, there is a predefined character-class available:
The class does feature also other kinds of character operations, such
condense
,replace
orsplit
.Guava has CharMatcher trimLeadingFrom and trimTrailingFrom
e.g.
CharMatcher.whitespace.trimTrailingFrom(s)