您可以使用以下代码:
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())
表示在
m找到匹配项时执行循环内给出的任何操作。并且我将
iby 的值递增
i++,因此很显然,这给出了
male cat一个字符串的数量。



