bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths

Loading lesson path

Learn/Java/Java How To's
Java•Java How To's

Java How To Count Words

Count Number of Words in a String

You can easily count the number of words in a string with the following example:

Example

String words = "One Two Three Four";
int countWords = words.split("\\s").length;
System.out.println(countWords);

Explanation: The method split("\\s") breaks the string into an array wherever it finds a space. In the example, the string "One Two Three Four" is split into 4 words. The length of that array tells us the total number of words.

Related Pages

Java String Methods

Previous

Java How To Generate Random Numbers

Next

Java How To - Count Vowels in a String