How do I count word occurrences in a string?

package org.kodejava.example.commons.lang;

import org.apache.commons.lang.StringUtils;

public class WordCountDemo {
    public static void main(String[] args) {
        // We have the source text we'll do the search on.
        String source = "From the download page, you can download the Java " +
            "Tutorials for browsing offline. Or you can just download " +
            "the examples.";
        // The word we want to count its occurrences
        String word = "you";

        // Using StringUtils.countMatches() method we can count the occurrences
        // frequency of a word/letter in the giver source of string.
        int wordFound = StringUtils.countMatches(source, word);

        // Print how many we have found the word
        System.out.println(wordFound + " occurrences of the word '" + word +
            "' was found in the text.");
    }
}

Here is the result of the code above.

2 occurrences of the word 'you' was found in the text.

Maven Dependencies

<!-- http://repo1.maven.org/maven2/commons-lang/commons-lang/2.6/commons-lang-2.6.jar -->
<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
</dependency>

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. Support me by donating.

Leave a Reply