Java program to count number of words in sentence

In this tutorial, we will see a simple java program to count number of words in sentence.

import java.util.Scanner;

public class StringOperator
{
   public static int countWordsinStr(String str){
        int count = 1;
        for(int i=0; i<=str.length()-1; i++){
            if(str.charAt(i) == ' ' && str.charAt(i+1)!=' '){
                count++;
            }
        }
        return count;
    }
   public static void main(String args[]){
        String str;
        Scanner scan = new Scanner(System.in);

        System.out.print("Enter a Sentence : ");
        str = scan.nextLine();

        System.out.print("Total number of words are " + countWordsinStr(str));
   }
}

Output:

Enter a Sentence : Java2Blog is a technical blog.
Total number of words are 5

That’s all about Java program to count number of words in sentence.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.