Skip to content

Count number of words in String Java Example

Count number of words in string Java example shows how to count number of words in string in Java using the charAt method and regular expression.

How to count number of words in Sting in Java?

1) Count the number of words in a string using the charAt method

We can use the charAt method of the String class to count the number of words as given below.

Output

Basically we looped through the characters of each of the string values and when we found a space character, we increased the word count by 1. By looking at the output, it seems that we did not take care of the last word since there is no space after the last word in the string. Also, if the string contains more than one consecutive spaces, our code ended up counting it as a separate word hence we got 4 word count in the sentence ” String count words “.

Let’s fix the problem. Have a look at the below given modified code for the countWords method.

Output

We made two changes, first, we added a while loop which skips through all the consecutive white spaces from the string. Second, we added else block which checks whether we have reached at end of the string and if we have, it increments the number of word by one.

Note: This approach does not work for word separators other than space (such as dot, comma or quotes).

2) Using Java regular expression

We can count the number of words using a regular expression pattern “\\s+” along with the split method.  The pattern “\\s” means space while the “\\s+” pattern means one or more spaces in a regular expression.

Output

Note: This approach also does not work for word separators other than the space character.

Instead of the “\\s+” pattern, the “\\w+” pattern should be used. The “\\w” pattern matches a word in a regular expression. For example, “Java Example.Hello” string will return word count as 2 using the “\\s+” pattern because “Example” and “Hello” are not separated by a space character but the dot. While the “\\w+” pattern will return word count as 3 since it matches words as given below.

Output

This example is a part of the Java String tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.