Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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:

4

An 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
0

Word 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
2

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.