在 Java 6 中查找子字符串
我查看了 String
Java 6 中的 API,我没有找到任何方法来计算特定子字符串在给定 String
中出现的次数。
例如,我想知道“is”
或“not”
在字符串“noisxxnotyynotxisi”
中出现了多少次。
我可以用循环做很长的路,但我想知道是否有更简单的方法。
谢谢。
编辑:我正在使用Java 6。
I looked through the String
API in Java 6 and I did not find any method for computing how many times a specific sub-string appears within a given String
.
For example, I would like to know how many times "is"
or "not"
appears in the string "noisxxnotyynotxisi"
.
I can do the long way with a loop, but I would like to know whether there is a simpler way.
Thanks.
Edit: I'm using Java 6.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
org.apache.commons.lang.StringUtils.countMatches 方法可能是首选方法。
org.apache.commons.lang.StringUtils.countMatches
method could be preferred.在不使用外部库的情况下,您可以在循环中使用
String.indexOf(String str, int fromIndex);
。更新 这个例子完全有效。
Without using an external library, you can use
String.indexOf(String str, int fromIndex);
in a loop.Update This example fully works.
您可以这样做,但循环会更快。
正如您所看到的,
如果文本以搜索值开始或结束,则这是正确的。 -1 参数阻止它删除尾随分隔符。
您可以使用带有 indexOf() 的循环,这更有效,但并不那么简单。
顺便说一句:Java 5.0 自 2007 年 8 月起就已停产。也许是时候看看 Java 6 了。(尽管文档非常相似)
You can do this, but a loop would be faster.
prints
As you can see this is correct if the text starts or ends with the search value. The -1 argument stops it removing trailing seperators.
You can use a loop with indexOf() which is more efficient, but not as simple.
BTW: Java 5.0 has been EOL since Aug 2007. Perhaps its is time to look at Java 6. (though the docs are very similar)