如何计算序列在Java字符串中出现的次数?

Joe*_*eph 9 java string

我有一个看起来像这样的字符串:

"Hello my is Joeseph. It is very nice to meet you. What a wonderful day it is!". 
Run Code Online (Sandbox Code Playgroud)

我想计算is字符串中的次数.

我怎么能用Java做到这一点?

Mik*_*x6r 30

一种简单的方法是使用Apache StringUtils countMatches

StringUtils.countMatches("Hello my is Joeseph. It is very nice to meet you. What a wonderful day it is!", "is");
Run Code Online (Sandbox Code Playgroud)


asg*_*sgs 11

int index = input.indexOf("is");
int count = 0;
while (index != -1) {
    count++;
    input = input.substring(index + 1);
    index = input.indexOf("is");
}
System.out.println("No of *is* in the input is : " + count);
Run Code Online (Sandbox Code Playgroud)

  • 您还可以使用index = input.indexOf("is",index + 1)而不是substring,然后使用indexOf.没有分析,我不确定,但怀疑这会更快.它也是1行代码;) (2认同)
  • 许多误报如"小姐","幸福".它也错过了大写的"Is","IS"或"iS".因此尽管OP已经接受了答案,但是从我这里得到了-1. (2认同)