Write Java program to count total number of words in a string


This program reads a string from the user and then counts the total number of words in the string. Here's how it works:

  • Declare a string variable text and an integer variable count.
  • Read a string input from the user using a Scanner object and store it in text.
  • Use a for loop to iterate through all the characters in the string except for the last one (since we will be checking the next character in the loop).
  • Check if the current character is a space (' ') and the next character is not a space. If this condition is true, increment count.
  • After the loop completes, add 1 to count to include the last word in the string.
  • Print the value of count as the total number of words in the string.

Source Code

import java.util.Scanner;
class NumberOf_Words
{
    public static void main(String args[])
    {
        String text;
        int count=0;
 
        Scanner input = new Scanner(System.in);         
        System.out.print("Enter the String : ");
        text = input.nextLine();
 
        for(int i=0; i<text.length()-1; i++)
        {
            if(text.charAt(i)==' ' && text.charAt(i+1)!=' ')
                count++;
        }
 
        System.out.println("Total Number of Words in String : "+ (count+1));
    }
}

Output

Enter the String : Wlecome Java Programs
Total Number of Words in String : 3

Example Programs