Q:

Java program to count total number of words in a string

0

Java program to count total number of words in a string

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Count Words in a String using Java program

//Java program to count words in a string.
 
import java.util.Scanner;
  
class CountWords
{
    public static void main(String args[])
    {
        String text;
        int countWords=0;
         
        Scanner SC=new Scanner(System.in);
         
        System.out.print("Enter string: ");
        text=SC.nextLine();
         
        //word count
        for(int i=0; i<text.length()-1; i++)
        {
            if(text.charAt(i)==' ' && text.charAt(i+1)!=' ')
                countWords++;
        }
         
        System.out.println("Total number of words in string are: "+ (countWords+1));
        //since last word does not contain and character after that
                     
    }
}

Output

    
    Enter string: Hello world
    Total number of words in string are: 2

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now