Problem: Write a Java Program to count the number of words in a given string or sentence.

Example:

Input:  I love Programming.
Output: 3

Input: hey programmer
Output: 2

Method 1: By Counting White Spaces

The number of words in a sentence is equal to the number of white spaces + 1.

So to count the number of words in the given string, we have to count the number of white spaces and add 1 to it.

import java.util.Scanner;
 
public class CountWords {
    public static void main(String args[]){
        Scanner in= new Scanner(System.in);
        String str;
        int c = 0;
 
        //Enter a string
        System.out.print("Enter a String/Sentence: ");
        str = in.nextLine();
        
        //Loop through the string
        for(int i=0; i<str.length(); i++){
            //check for white space and increment counter
            if(str.charAt(i) == ' ')
                c++;                      
        }
        
        //add 1 more to the counter value
        c = c+1;   
        
        //output the counter value
        System.out.println("Number of words: "+c);
    }
}

Output:

Enter a String/Sentence: hey programmer
Number of words: 2

Note: This method will not give the correct result if more than one white space exists simultaneously in the sentence.

Method 2: By Splitting String into Words

The idea is to split the given string into an array of words using the split() method and output the length of the array to get the actual count of words.

import java.util.Scanner;
 
public class Main {
    public static void main(String args[]){
        Scanner in= new Scanner(System.in);
        String str;
 
        //Enter a string
        System.out.print("Enter a String/Sentence: ");
        str = in.nextLine();
        
        //split the string into an array of words
        String words[] = str.split("\\s+");
        
        //output the length of the array
        System.out.println("Number of words: "+words.length);
    }
}

Output:

Enter a String/Sentence: This is the website for programmers.
Number of words: 6

Leave a Reply