Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the number of Occurrences of a Word in a String

Tags:

java

string

regex

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?

like image 276
Java Nerd Avatar asked Mar 21 '14 18:03

Java Nerd


People also ask

How do you count occurrences of words in a string?

First, we split the string by spaces in a. Then, take a variable count = 0 and in every true condition we increment the count by 1. Now run a loop at 0 to length of string and check if our string is equal to the word.

How do you count the number of times a word appears in a string Python?

count() Python: Using Strings. The count() method can count the number of occurrences of a substring within a larger string. The Python string method count() searches through a string. It returns a value equal to the number of times a substring appears in the string.

How do you count the number of occurrences of a character in a string?

The string count() method returns the number of occurrences of a substring in the given string. In simple words, count() method searches the substring in the given string and returns how many times the substring is present in it.


5 Answers

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.

like image 53
Amit Joki Avatar answered Sep 30 '22 11:09

Amit Joki


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;
like image 31
donfuxx Avatar answered Sep 30 '22 10:09

donfuxx


StringUtils in apache commons-lang have CountMatches method to counts the number of occurrences of one String in another.

   String input = "i have a male cat. the color of male cat is Black";
   int occurance = StringUtils.countMatches(input, "male cat");
   System.out.println(occurance);
like image 41
2787184 Avatar answered Sep 30 '22 10:09

2787184


Java 8 version:

    public static long countNumberOfOccurrencesOfWordInString(String msg, String target) {
    return Arrays.stream(msg.split("[ ,\\.]")).filter(s -> s.equals(target)).count();
}
like image 38
Karol Król Avatar answered Sep 30 '22 12:09

Karol Król


This static method does returns the number of occurrences of a string on another string.

/**
 * Returns the number of appearances that a string have on another string.
 * 
 * @param source    a string to use as source of the match
 * @param sentence  a string that is a substring of source
 * @return the number of occurrences of sentence on source 
 */
public static int numberOfOccurrences(String source, String sentence) {
    int occurrences = 0;

    if (source.contains(sentence)) {
        int withSentenceLength    = source.length();
        int withoutSentenceLength = source.replace(sentence, "").length();
        occurrences = (withSentenceLength - withoutSentenceLength) / sentence.length();
    }

    return occurrences;
}

Tests:

String source = "Hello World!";
numberOfOccurrences(source, "Hello World!");   // 1
numberOfOccurrences(source, "ello W");         // 1
numberOfOccurrences(source, "l");              // 3
numberOfOccurrences(source, "fun");            // 0
numberOfOccurrences(source, "Hello");          // 1

BTW, the method could be written in one line, awful, but it also works :)

public static int numberOfOccurrences(String source, String sentence) {
    return (source.contains(sentence)) ? (source.length() - source.replace(sentence, "").length()) / sentence.length() : 0;
}
like image 33
Lucio Avatar answered Sep 30 '22 12:09

Lucio