Flash cards
Review the key moves
What is the main idea behind Java How To Count Words?
Lesson checks
Practice each idea before moving on
Short Mimo-style checks built from this lesson's code, terms, and sequence.
Which statement best captures the main point of this lesson?
Complete the missing token from the example code.
___ words = "One Two Three Four";Put the learning moves in the order that makes the concept easiest to apply.
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