Java Nerd Java Nerd - 1 year ago 93
Java Question

Count the number of Occurrences of a Word in a 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!

What I am trying is:

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

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

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

Answer Source

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()) {
System.out.println(i); // Prints 2


What it does?

It matches "male cat".


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download