Java 相当于 python 的 String lstrip()?
我想删除字符串中的前导空格,但不删除尾随空格 - 所以trim() 不起作用。在 python 中,我使用 lstrip(),但我不确定 Java 中是否有等效的函数。
作为一个例子,
" foobar "
如果可能的话,
"foobar "
我也想避免使用正则表达式。
Java 中是否有内置函数,或者我是否必须创建自己的方法来执行此操作? (以及我能实现这一目标的最短方法是什么)
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 "
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用 Apache Commons Lang 的
StringUtils
类,该类具有stripStart()
方法(还有更多)。You could use the
StringUtils
class of Apache Commons Lang which has astripStart()
method (and many many more).您可以在正则表达式中执行此操作:
You could do this in a regular expression:
Guava 具有
CharMatcher.WHITESPACE.trimLeadingFrom(string)
。这本身与其他实用程序库的同一事物的版本没有什么不同,但是一旦您熟悉了CharMatcher
,您就会知道如何在其中执行大量的文本处理操作。一致、可读、高性能的方式。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 withCharMatcher
there is a tremendous breadth of text processing operations you'll know how to perform in a consistent, readable, performant manner.从 Java11 开始,您可以在字符串上使用
.stripLeading()
来删除前导空格,并使用.stripTrailing()
来删除尾随空格。可以在此处找到相关文档: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#stripLeading()
例子:
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:
org.springframework.util.StringUtils.trimLeadingWhitespace(String)
org.springframework.util.StringUtils.trimLeadingWhitespace(String)