How to Count Words in a String in Java
The Challenge
Count the number of words in a string - words are separated by spaces!
Solution
Method 1: Using split()
String text = "Java is fun to learn";
String[] words = text.split("\\s+");
int wordCount = words.length;
System.out.println("Word count: " + wordCount);
// Output: Word count: 5Method 2: Using StringTokenizer
import java.util.StringTokenizer;
String text = "Java is fun to learn";
StringTokenizer tokenizer = new StringTokenizer(text);
int wordCount = tokenizer.countTokens();
System.out.println("Word count: " + wordCount);
// Output: Word count: 5Method 3: Manual Counting
String text = "Java is fun to learn";
int wordCount = 0;
boolean isWord = false;
for (int i = 0; i < text.length(); i++) {
if (Character.isWhitespace(text.charAt(i))) {
isWord = false;
} else if (!isWord) {
wordCount++;
isWord = true;
}
}
System.out.println("Word count: " + wordCount);
// Output: Word count: 5Did You Know?
The regex \\s+ matches one or more whitespace characters (spaces, tabs, newlines). This handles multiple spaces between words!
Watch Out!
Handle empty strings and leading/trailing spaces:
String text = " Java is fun ";
String[] words = text.trim().split("\\s+");
int wordCount = text.trim().isEmpty() ? 0 : words.length;Real-World Use Cases
- Text editors: Display word count
- SEO tools: Analyze content length
- Social media: Enforce character/word limits
- Document analysis: Calculate reading time
›Short versionOpen if you only have a minute.
- trim, then split on whitespace runs with \s+.
- split(" ") treats each extra space as an empty word.
- "".split("\\s+") returns a one-element array, so an all-space string counts as 1 unless you check empty first.
- Punctuation stays attached to the token. This recipe does not know what a word is in every language.
Count words
Count whitespace-separated tokens, without counting empty tokens from repeated spaces.
Working approach
- Trim the string.
- If nothing remains, return 0.
- Otherwise split on \\s+ and return the length.
Walk the sample
- Input " Java is fun "
- Trim leaves "Java is fun"
- Split on whitespace runs yields three tokens
- The count is 3
The trap
The empty string is the case the sample "Java is fun" never hits. After trim, split still reports one token.
static int wordCount(String text) {
String trimmed = text.trim();
if (trimmed.isEmpty()) {
return 0;
}
return trimmed.split("\\s+").length;
}What does " ".trim().split("\\s+").length return?
trim leaves the empty string. "".split("\\s+") returns an array of one empty string, so the length is 1.
Return 0 when the trimmed text is empty. split(" ") on "a b" has the other bug: it returns three tokens because the gap is an empty string.
Time O(n), space proportional to the number of tokens.
Easy to get wrong
- Splitting on a single space and counting the empty strings between doubles.
- Splitting before checking that trim left some text.