计算字符串中Word的出现次数 [英] Count the number of Occurrences of a Word in a String

查看:270
本文介绍了计算字符串中Word的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java Strings的新手,问题是我想要计算String中特定单词的出现次数。假设我的字符串是:

I am new to Java Strings the problem is that I want to count the Occurrences of a specific word in a String. Suppose that my String is:

i have a male cat. the color of male cat is Black

现在我不想拆分它所以我想搜索一个词是公猫。它在我的字符串中出现两次!

Now I dont want to split it as well so I want to search for a word that is "male cat". it occurs two times in my string!

我正在尝试的是:

int c = 0;
for (int j = 0; j < text.length(); j++) {
    if (text.contains("male cat")) {
        c += 1;
    }
}

System.out.println("counter=" + c);

它给了我46个计数器值!那么解决方案是什么?

it gives me 46 counter value! So whats the solution?

推荐答案

您可以使用以下代码:

String in = "i have a male cat. the color of male cat is Black";
int i = 0;
Pattern p = Pattern.compile("male cat");
Matcher m = p.matcher( in );
while (m.find()) {
    i++;
}
System.out.println(i); // Prints 2

演示

它匹配公猫

while(m.find())

表示,在 m 找到匹配项。
我正在通过 i ++ 递增 i 的值,显然,这给出了公猫字符串已经获得。

indicates, do whatever is given inside the loop while m finds a match. And I'm incrementing the value of i by i++, so obviously, this gives number of male cat a string has got.

这篇关于计算字符串中Word的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆