Java equivalent of python's String lstrip()?
I'd like to remove the leading whitespace in a string, but without removing the trailing whitespace - so trim() won't work. In python I use lstrip(), but I'm not sure if there's an equivalent in Java.
As an example
" foobar "
开发者_如何学Go
should become
"foobar "
I'd also like to avoid using Regex if at all possible.
Is there a built in function in Java, or do I have to go about creating my own method to do this? (and what's the shortest way I could achieve that)
You could use the StringUtils
class of Apache Commons Lang which has a stripStart()
method (and many many more).
You could do this in a regular expression:
" foobar ".replaceAll("^\\s+", "");
Guava has CharMatcher.WHITESPACE.trimLeadingFrom(string)
. This by itself is not that different from other utility libraries' versions of the same thing, but once you're familiar with CharMatcher
there is a tremendous breadth of text processing operations you'll know how to perform in a consistent, readable, performant manner.
Since Java11 you can use .stripLeading()
on a String to remove leading white-spaces and .stripTrailing()
to remove trailing white-spaces.
The documentation for this can be found here: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#stripLeading()
Example:
String s = " Hello there. ";
s.stripLeading(); // "Hello there. "
s.stripTrainling(); // " Hello there."
s.strip(); // "Hello there."
org.springframework.util.StringUtils.trimLeadingWhitespace(String)
精彩评论