Count Words in Java: Solution, Explanation & Practice
Count words in a sentence
Problem summary
Write a program that counts the number of words in a sentence.
Starter code
public class Main {
public static void main(String[] args) {
String sentence = "Java is a programming language"; // Test case 1
// Count words
// Print: Word count: <result>
}
}Expected output and test cases
- 5 words in sentence
Word count: 5
- Single word
Word count: 1
- Three words
Word count: 3
Hints
- Split by space: .split(" ")
- Count array length after split
- Handle multiple spaces with .split("\\s+")
Validated solution
Reveal Java solution
public class Main {
static int wordCount(String text) {
String trimmed = text.trim();
return trimmed.isEmpty() ? 0 : trimmed.split("\\s+").length;
}
public static void main(String[] args) {
System.out.println("Word count: " + wordCount("Java programs can be readable"));
}
}How to approach the problem
Trim first so leading and trailing whitespace cannot create a fake word. Splitting the remaining text on one-or-more whitespace characters treats repeated spaces, tabs, and newlines as one separator.
Approach
- Trim the input.
- Return zero if nothing remains.
- Split on the whitespace run pattern.
Time and space complexity
Time: O(n). Space: O(n).
Edge cases to test
- Whitespace-only input has zero words.
- A word definition involving punctuation or apostrophes needs a more specific tokenizer.
Common mistakes
- Calling split on an empty trimmed string and treating the result as one word.
- Splitting only on a literal single space.
Follow-up challenge
Count words while preserving quoted phrases as one token.
Related Strings exercises
- Practice String Palindrome in Java
- Practice Count Vowels in Java
- Practice First Non-Repeating Character in Java
Practice all Strings exercises · Run this idea in the Java compiler