How to find the frequecy of a word in a given sentence

Given some text and a word. How do we find the frequency of the word?

In this post we will see a Java program which finds it with just a few lines of code using regular expression matching.

Java provides utilities for matching the regular expressions using java.util.regex package. In our program we utilize two of them namely Pattern, and Matcher. These are the fundamental classes in this package.

In the following code reader is an object of class Scanner which is used for reading the input from the keyboard. The Pattern class does not have a public constructor, we have to create an object of that class using the compile() method by passing the pattern. Similarly the Matcher class also does not have a public constructor, and it’s object should be returned by matcher() method of the Pattern object.

The matcher class provides a method called find() which tries to find the next instance of the pattern in the given text. If it finds the pattern it returns true otherwise it returns false.

Here is the Java code.

import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Main {
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
String sentence = reader.nextLine();
String word = reader.nextLine();
Pattern p = Pattern.compile(word);
Matcher m = p.matcher(sentence);
int count = 0;
while( m.find())
count++;
System.out.println("The word '" + word + "' occurred " + count + " time(s)");
}
}