Java Program to Count Words in String
You can count words in a string in Java by splitting the string with
split("\\s+") and then getting the length of the resulting array, like int count = str.trim().split("\\s+").length;.Examples
InputHello world
Output2
Input Java programming is fun
Output4
Input
Output0
How to Think About It
To count words in a string, first remove extra spaces at the start and end using
trim(). Then split the string by spaces using split("\\s+") which divides the string wherever there is one or more spaces. The number of parts after splitting is the number of words.Algorithm
1
Get the input string.2
Remove leading and trailing spaces using trim.3
Check if the string is empty after trimming; if yes, return 0.4
Split the string by one or more spaces using split("\\s+").5
Count the number of elements in the split array.6
Return the count as the number of words.Code
java
public class WordCount { public static void main(String[] args) { String str = "Java programming is fun"; str = str.trim(); if (str.isEmpty()) { System.out.println(0); } else { String[] words = str.split("\\s+"); System.out.println(words.length); } } }
Output
4
Dry Run
Let's trace the input "Java programming is fun" through the code
1
Input string
"Java programming is fun"
2
Trim spaces
"Java programming is fun" (no change)
3
Check if empty
Not empty, continue
4
Split by spaces
["Java", "programming", "is", "fun"]
5
Count words
4
6
Print result
4
| Step | Words Array | Count |
|---|---|---|
| Split | ["Java", "programming", "is", "fun"] | 4 |
Why This Works
Step 1: Trim the string
Using trim() removes spaces at the start and end so they don't count as words.
Step 2: Split by spaces
Splitting by "\\s+" divides the string at one or more spaces, separating words.
Step 3: Count the words
The length of the split array is the total number of words in the string.
Alternative Approaches
Using StringTokenizer
java
import java.util.StringTokenizer; public class WordCount { public static void main(String[] args) { String str = "Java programming is fun"; StringTokenizer st = new StringTokenizer(str); System.out.println(st.countTokens()); } }
StringTokenizer is older and less flexible but simple for counting words separated by spaces.
Using Scanner
java
import java.util.Scanner; public class WordCount { public static void main(String[] args) { String str = "Java programming is fun"; Scanner sc = new Scanner(str); int count = 0; while (sc.hasNext()) { sc.next(); count++; } sc.close(); System.out.println(count); } }
Scanner reads tokens separated by whitespace, useful for more complex input parsing.
Complexity: O(n) time, O(n) space
Time Complexity
The program scans the entire string once to split it, so time grows linearly with string length.
Space Complexity
Splitting creates an array of words, so space grows with the number of words in the string.
Which Approach is Fastest?
Using split is simple and fast for most cases; StringTokenizer and Scanner add overhead but offer more control.
| Approach | Time | Space | Best For |
|---|---|---|---|
| split("\\s+") | O(n) | O(n) | Simple and fast word count |
| StringTokenizer | O(n) | O(n) | Legacy code or simple tokenization |
| Scanner | O(n) | O(n) | Complex input parsing with tokens |
Always trim the string before splitting to avoid counting empty spaces as words.
Beginners often forget to trim the string, causing incorrect word counts due to leading or trailing spaces.