Java program to count words in a given string


A string is a class in Java that stores a series of characters enclosed within double quotes. Those characters act as String-type objects. The aim of this article is to write Java programs that count words in a given string. Counting words of the given strings can be solved using the string manipulation techniques. In Java interviews, questions from string manipulation are very frequent, hence, it is important to understand this problem properly.

Java Program to Count Words in a given String

Before jumping to the example programs, let's understand the problem statement with the help of an example.

Input

String = "You are on Tutorials Point website";

Output

Number of words in the given string: 6

We can observe that the words in the string are separated by whitespace (' ') and to instruct this information to the Java compiler, we will check whether the character at current index is a whitespace or a letter. If it is whitespace and the next character is a letter, we will increment the counter variable to specify we have encountered a word.

Now, let's discuss a few Java programs to count words in a given string.

Example 1

The following example illustrates how we can use the while loop to print the number of words in a given string.

Approach

  • First, initialize a string whose words are to be counted.

  • Then, declare a counter variable to store the number of words.

  • Next, take a while loop that will iterate through each character of string. Inside this loop, define an if block to check whitespace using the 'charAt()' method. If we encounter the space, we will increment the counter.

  • In the end, print the result and exit.

public class Example1 { 
   public static void main(String args[]) { 
      // initializing a string
      String msg = "Tutorials Point Welcomes You!!";
      System.out.println("The given String is: " + msg);
      // initial count of the words
      int total = 1;
      // loop variable
      int i = 0; 
      // while loop to count the number of words
      while (i < msg.length()) { 
         // checking if the current character is space or not
         if ((msg.charAt(i) == ' ') && (msg.charAt(i + 1) != ' '))  {
            total++;  // incrementing the word count
         }
         i++; // incrementing loop variable
      } 
      // printing the result
      System.out.println("Number of words in the given string: " +  total);
   } 
}

Output

The given String is: Tutorials Point Welcomes You!!
Number of words in the given string: 4

Example 2

In this example, we will use the for loop instead of while loop to check the word count of given string.

public class Example2 {
   public static void main(String[] args) {
      // initializing a string
      String msg = "Tutorials Point Welcomes You!!";
      System.out.println("The given String is: " + msg);
      // initial count of the words
      int total = 1;
      // for loop to count the number of words
      for (int i = 0; i < msg.length(); i++) {
         // checking if current character is space or not
         if ((msg.charAt(i) == ' ') && (msg.charAt(i + 1) != ' ')) {
            total++; // incrementing the word count 
         }
      }
      // printing the result
      System.out.println("Number of words in the given string: " +  total);
   }
}

Output

The given String is: Tutorials Point Welcomes You!!
Number of words in the given string: 4

Example 3

This is another Java program that will check the count of words in a given string using the built-in method named 'split()'. We will use the '\s+' delimiter as an argument of split() method to separate the words from whitespace and to check the number of words, we will use the length property of string.

public class Example3 {
   public static void main(String[] args) {
      // initializing a string
      String msg = "Tutorials Point Welcomes You!! ";
      System.out.println("The given String is: " + msg);
      // To Split the string into words
      String[] arrayStr = msg.split("\s+");
      // To Count the number of words
      int totalWord = arrayStr.length;
      // printing the result
      System.out.println("Number of words in the given string: " + totalWord);
   }
}

Output

The given String is: Tutorials Point Welcomes You!! 
Number of words in the given string: 4

Conclusion

In this article, we have learned what is a string and how we can check the number of words of a given string in Java. For this string manipulation operation, we have used the in-built methods of String such charAt() and split() along with the while and for loops.

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 10-Aug-2023

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements