Java program to count number of words in a string

Previous
Next

In this post, we will see Java program to find number of words in a String.

Problem

Find the number of words in a String.

For example:
There are 6 words in below String

welcome to java tutorial on Java2blog

Algorithm

The algorithm will be very simple.

  • Initialize count with 1 as if there are no spaces in the string, then there will be one word in the String.
  • Check if you encounter any space.
  • Once you find the space, check it next character. If it is not space then we found a word in the String.Increment the count variable.
  • Once you reach end of String, count variable will hold number of words in the String.

Program

When you run above program, you will get below output:

Number of words in a string : 6

that’s all about Java program to count number of words in a string.

Previous
Next

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog