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

11

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

"Hello my is Joeseph. It is very nice to meet you. What a wonderful day it is!". 

我想要计算字符串中出现is的次数。

在Java中,我该如何做到这一点?


2
你能否发布一下你自己尝试过的内容?还有那个:“是小姐吗?” - Bart Kiers
@Bart Kiers,我相信我们只需要寻找“ is ”而不是“is”,就可以避免这个问题 ;) - Joeseph
1
你不理解它的本质。 - asgs
通过寻找“是”,你会错过:“是,”和“是!”等。 - Bart Kiers
7个回答

33

一种简单的方法是使用Apache StringUtils中的countMatches函数。


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

1
使用Spring框架StringUtils.countOccurrencesOf(string, "is");函数。 - stivlo
1
Spring的StringUtils不是主要用于框架内部吗?也就是说,它可以工作,但在这方面Apache显然更好。 - Michael Piefel
运行得很好。谢谢。 - An̲̳̳drew

15
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);

@jzd 同意,感谢指出错误。 - asgs
1
@asgs,您无法恢复已删除的评论,并且由于您在前五分钟内编辑了答案,因此没有修订历史记录。所以没有什么可以学习的了。 - jzd
运行得非常好。不需要任何花哨的库。谢谢。 - Joeseph
2
你也可以使用 index = input.indexOf("is", index+1) 代替 substring 和 indexOf。没有进行性能分析,我不确定,但猜测这样会更快。而且代码少了一行 ;) - Mikezx6r
2
许多误报,例如“miss”、“bliss”。它还会错过大写的“Is”、“IS”或“iS”。因此,尽管OP已经接受了答案,但我会给出-1。 - Bart Kiers
显示剩余2条评论

4
如果您更喜欢使用正则表达式,这里有一个正则表达式解决方案:
String example = "Hello my is Joeseph. It is very nice to meet you. isWhat a wonderful day it is!";
Matcher m = Pattern.compile("\\bis\\b").matcher(example);

int matches = 0;
while(m.find())
    matches++;

System.out.println(matches);

在这种情况下,“isWhat”中的“is”被忽略了,因为模式中有\b边界匹配器。

2
String haystack = "Hello my is Joeseph. It is very nice to meet you. What a wonderful day it is!";
haystack.toLowerCase();
String needle = "is";

int numNeedles = 0;

int pos = haystack.indexOf(needle);

    while(pos >= 0 ){

      pos = pos + 1;
      numNeedles = numNeedles + 1;

      pos = haystack.indexOf(needle,pos);

    }

 System.out.println("the num of " +needle+ "= " +numNeedles);

1
一个 char 类型的变量从何时开始能够容纳多个字符? - LuigiEdlCarno
注意到我的错误并进行了编辑。 - Betsy

1

按每个空格进行分割,并使用循环检查输出的字符串数组


如果要检查的字符串中有空格怎么办? - Daniel DiPaolo
在这种情况下,他不会数字符串中“is”的数量 >_< ,但如果需要,他可以使用正则表达式。 - nyyrikki

1
你可以在这里找到代码。 它看起来很像Robby的代码。

1

这考虑了“replace”长度的影响

String text = "a.b.c.d";
String replace = ".";
int count = (text.length()- (text.replaceAll(replace, "").length())) / replace.length();
System.out.println(count)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接