# Program to count number of words in a string (multiple spaces) – Java

This program takes a string from the user and counts the total number of words in it. No matter how many white spaces are there in the string, it will only count the number of words.

Ex:
(i) Hi this is Rupam.
Result: 4

(ii)     Hi    this     is Rupam.
Result: 4

### LOGIC

Here to find the total number of words in a string, we have to count the number of spaces. Because every word in a sentence is separated by a whitespace, right? The total number of spaces + 1 will be the total number of words. So if we count the number of spaces in a sentence, we will get the total number of words easily.

Ex: This program will count the number of words.

Result: 8

Here total number of spaces= 7

So total number of words= 7+1= 8

Now there is a problem in this logic. This logic will only work if there is only one space between every word. What if there are more than one white spaces between the words? The result will be wrong.

So we have to apply another condition along with the above condition. Count the space only if it is not preceded by any other white space.

Ex:
This        program      will     count     the number of words.

Result: 8

### CODE EXPLANATION

(i) Here we are taking a string from the user and assigning it to a variable.

(ii) Return the length of the string using length() method.

(iii) Using For loop we are checking each character (charAt method) in the string given by user.

Inside the for loop we are using If..else statement to check if the character is a whitespace or not. We are also checking if it is preceded by any other white space or not.

The condition will satisfy only if both the above two conditions are true.

(iv) If it satisfies, increment the word count by one.