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
package org.arpit.java2blog.java8;
public class CountNumberOfWordsInStringMain {
public static void main(String[] args) {
String str = "welcome to java tutorial on Java2blog";
int count = 1;
for (int i = 0; i < str.length() - 1; i++)
{
if ((str.charAt(i) == ' ') && (str.charAt(i + 1) != ' '))
{
count++;
}
}
System.out.println("Number of words in a string : " + count);
}
}
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.