计算字符串中单词的出现次数它有什么作用?

2022-09-02 04:56:22

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

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

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

我正在尝试的是:

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

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

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


答案 1

您可以使用以下代码:

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

演示

它有什么作用?

它匹配 ."male cat"

while(m.find())

指示,在查找匹配项时执行循环中给出的任何内容。我正在递增 by 的值,所以很明显,这给出了字符串的数目。mii++male cat


答案 2

如果你只是想要计数,那么我会这样做:"male cat"

String str = "i have a male cat. the color of male cat is Black";
int c = str.split("male cat").length - 1;
System.out.println(c);

如果你想确保不匹配,那么在拆分正则表达式中使用单词边界:"female cat"\\b

int c = str.split("\\bmale cat\\b").length - 1;