Java

How to Count the Number of Words in a String Using Java?

In Java, counting the number of words in a string is to determine the number of individual words in a given text or input string. This can be useful in a variety of text-processing applications, such as word-counting programs, text analysis tools, and natural language processing (NLP) systems. For example, validate the length of user input in a form or check if a password meets the required minimum length or not.

This guide will illustrate the following content:

How to Count the Number of Words in a String from a User Input String?

To count the number of words in a string using Java, users can get the string input from the user. In this process, split the complete string into words through the “split()” method. After that, get the length of the resulting array of words utilizing the “length” property.

Here’s an example code that implements this process:

Code

import java.util.Scanner;

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

        // Get the input string from the user
        System.out.print("Enter a string: ");
        String inputString = scanner.nextLine();

        // Split the string into words
        String[] words = inputString.split("\\s+");

        // Get the number of words
        int numWords = words.length;

        // Print the result
        System.out.println("Number of words: " + numWords);
    }
}

The description of the above code is given below:

  • First, import the “Scanner” class to take input from the user side.
  • Then prompt the user to enter a string using System.out.print() and read the input using the scanner.nextLine().
  • Next, split the input string into words using the split() method, which takes a regular expression pattern as an argument.
  • There, use the pattern \\s+, which matches one or more whitespace characters (spaces, tabs, and newlines), to split the string into words.
  • Finally, get the length of the resulting array of words using the length property and print the number of words to the console using System.out.println().

Output

The output shows that users enter an input string whose word count is 5 in the terminal.

How to Count the Number of Words in a String from a Predefined String?

For counting the number of words in a predefined string. Here is an example of a Java program that counts the number of words in each string:

Code

public class WordCount {
    public static void main(String[] args) {
        String str = "This is an example sentence. Always believe in yourself";
        int wordCount = 0;

        // Loop through the string, counting each word
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == ' ') {
                wordCount++;
            }
        }

        // Add one to the word count to account for the last word
        wordCount++;

        // Print the result
        System.out.println("The number of words in the string is: " + wordCount);
    }
}

The description of the above code is mentioned below;

  • First, initialize a string and a counter variable to zero.
  • Then loop through the string to check each character to see if it is a space. If it is, increase the word count.
  • After the loop is finished, add one to the word count to account for the last word (which will not have a space after it).

Output

The output prints out the result which is the number of word count that is “9” in the console window.

Conclusion

To count the number of words in a string using Java, first split the string into words using the “split()” method. It accepts an input string as an argument. It matches one or more whitespace characters, i.e., newlines, spaces, and tabs. Once the string is split into an array of words, users can get the length of the array utilizing the “length” property.

About the author

Syed Minhal Abbas

I hold a master's degree in computer science and work as an academic researcher. I am eager to read about new technologies and share them with the rest of the world.