How to count words in a string
Short answer
Strip the ends and split the string by one or more whitespace characters:
void main() {
String text = " Java is a language ";
int count = text.strip().split("\\s+").length;
IO.println(count);
}Output:
4An empty string
"".split(...) returns an array with one empty string, so check for empty text separately:
int countWords(String text) {
return text.isBlank() ? 0 : text.strip().split("\\s+").length;
}
void main() {
IO.println(countWords("one two"));
IO.println(countWords(" "));
}Output:
2
0Word frequency
To find out how many times each word appears, group the words and count them:
void main() {
String text = "to be or not to be";
Map<String, Long> counts = Arrays.stream(text.split("\\s+"))
.collect(Collectors.groupingBy(word -> word, TreeMap::new, Collectors.counting()));
IO.println(counts);
}Output:
{be=2, not=1, or=1, to=2}Common mistake
Splitting by a single space. Double spaces produce empty "words", and the count is wrong:
void main() {
String text = "one two";
IO.println(text.split(" ").length);
IO.println(text.split("\\s+").length);
}Output:
3
2Functions used in this recipe
- String.split() — Splits a string into an array of parts by a separator.
- String.strip() — Removes any Unicode whitespace from both ends of a string.
- String.isBlank() — Checks whether a string is empty or contains only whitespace.
- Collectors.groupingBy() — A collector that sorts elements into groups that share a key.