Java Program to Count Occurrences of Words in a String

Introduction

Counting the occurrences of each word in a string is a common task in text processing and analysis. This guide will show you how to create a Java program that counts and displays the frequency of each word in a given string.

Problem Statement

Create a Java program that:

  • Takes a string as input.
  • Counts and displays the frequency of each word in the string.

Example 1:

  • Input: "This is a test. This test is easy."
  • Output: This: 2, is: 2, a: 1, test: 2, easy: 1

Example 2:

  • Input: "Java is great and Java is powerful"
  • Output: Java: 2, is: 2, great: 1, and: 1, powerful: 1

Solution Steps

  1. Prompt for Input: Use the Scanner class to read a string input from the user.
  2. Split the String into Words: Use the split() method to divide the string into individual words.
  3. Use a HashMap to Track Word Frequencies: Iterate through the array of words and store the frequency of each word in a HashMap.
  4. Display the Word Frequencies: Print the frequency of each word in the string.

Java Program

Java Program to Count Occurrences of Words in a String

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * Java Program to Count Occurrences of Words in a String
 * Author: https://www.javaguides.net/
 */
public class WordFrequencyCounter {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Step 1: Prompt the user for input
        System.out.print("Enter a string: ");
        String input = scanner.nextLine();

        // Step 2: Split the string into words
        String[] words = input.toLowerCase().split("\\s+");

        // Step 3: Use a HashMap to track word frequencies
        Map<String, Integer> wordCountMap = new HashMap<>();

        for (String word : words) {
            wordCountMap.put(word, wordCountMap.getOrDefault(word, 0) + 1);
        }

        // Step 4: Display the word frequencies
        System.out.println("Word frequencies:");
        for (Map.Entry<String, Integer> entry : wordCountMap.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

Explanation

  • Input: The program prompts the user to enter a string.
  • Splitting the String: The string is converted to lowercase and split into individual words using the split() method. The regular expression "\\s+" is used to match any whitespace characters (spaces, tabs, etc.), ensuring that all words are separated correctly.
  • Tracking Word Frequencies: The program uses a HashMap to count the occurrences of each word in the array. The getOrDefault method simplifies the process of incrementing the count.
  • Displaying Frequencies: The program then iterates over the HashMap to display each word and its corresponding frequency.

Output Example

Example 1:

Enter a string: This is a test. This test is easy.
Word frequencies:
this: 2
is: 2
a: 1
test: 2
easy.: 1

Example 2:

Enter a string: Java is great and Java is powerful
Word frequencies:
java: 2
is: 2
great: 1
and: 1
powerful: 1

Example 3:

Enter a string: Hello world hello
Word frequencies:
hello: 2
world: 1

Conclusion

This Java program effectively counts the occurrences of each word in a string using a HashMap. By tracking the frequency of each word, the program can display the exact number of times each word appears in the input string. This approach is practical for various text processing tasks, such as analyzing text, ensuring data integrity, or generating word frequency statistics.

Related Java String Programs with Output

Comments