Java Programs

Please click on 1-2 Ads to keep this website's Study Material FREE and regularly Updated.

Program 41: Write a Java program to count number of words in a string.

CountWords.java

import java.util.Scanner;

public class CountWords
{
	//Method to count number of words in a string.
	public static int countWords(String str){
        int count =0;
        for(int i=0; i < str.length();i++)
        {
            if(str.charAt(i)==' ')
            {
                count++;
            }
        }
		return count+1;
	}
	
	//Main Method
	public static void main(String[] args)
	{
		Scanner s = new Scanner(System.in);
		System.out.println("Enter the string");
		String str = s.nextLine();

		System.out.println("Number of words: ");
		System.out.println(CountWords.countWords(str));
	}
}



If you have any suggestion or found any error in the above program, then do let us know at [email protected] or just comment below.