姬長信(Redy)

java – 计算字符串中Word的出现次数


我是Java Strings的新手,问题是我想要计算String中特定单词的出现次数.假设我的String是:
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计数值!那么解决方案是什么?