ADVERTISEMENT
ADVERTISEMENT

Java program to count total number of words in a string

This program will count total number of words in a string in Java. In this program we will read a string from the user and count total number of words in that.

The logic behind to implement this logic - Check two consecutive characters, if first character is space and next is not space, if the condition is true we will increase the counter.

Example

    Input:
    Enter string: Hello world

    Output:
    Total number of words in string are: 2

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

Core Java Example Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.