Java String Handling RegEx

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. This example also shows how to count words in string using Java regular expression.

How to count number of words in Sting in Java?

There are two ways in which we can count number of words in String in Java, without using regular expression and with using regular expression as given below.

1) Count number of words in String using charAt method

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

Output

Basically we looped through each of the String values and when we found the 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 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 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) Count number of words in String using Java regular expression

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

Output

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

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

Output

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

 

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.

Tags