Count the number of Occurrences of a Word in a String

You can use the following code:

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

Demo

What it does?

It matches "male cat".

while(m.find())

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.


If you just want the count of "male cat" then I would just do it like this:

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

and if you want to make sure that "female cat" is not matched then use \\b word boundaries in the split regex:

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

Tags:

Java

String

Regex