Count Words in Java: 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+")
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