We need to write a program in java that takes input a string (basically a sentence) and print the number of words present in the string.

Example:

The trick is the number of words = number of blank_space + 1.

So all we need to do is to count the number of spaces, add 1 and output it.

Steps to Count Number of Words in a Sentence in Java

  • Take input a string (str).
  • Run for loop (i) from 0 to str.length()-1.
  • Check if the character at position (i) is blank space i.e str.charAt(i) == ‘ ‘.
  • If yes then increment the counter (c++).
  • When loop ends, add 1 to the counter (c +=1).
  • (c) is the count of words in the string.

Count Words in a String in Java

Output

If you have any suggestion or doubt then comment below.

Leave a Reply

Close Menu