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

Example:

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.

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.

Output:

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

Leave a Reply

nine − 8 =