Count number of words in a string

Table of Contents

In this post, we will see how 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 how to count number of words in a string.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *