๐ข Java: How to Count Words in a String
๐งฒ Introduction โ Why Count Words in Java?
Whether you’re building a text editor, analyzing user input, or creating a word frequency counter, knowing how to count words in a string is a practical skill in Java.
In this guide, you’ll learn:
- How to split a string into words
- Count words using
split()
andScanner
- Handle edge cases like multiple spaces or punctuation
๐งฎ Method 1: Count Words Using split(" ")
public class WordCounter {
public static void main(String[] args) {
String text = "Java is a powerful programming language";
String[] words = text.trim().split("\\s+");
System.out.println("Word count: " + words.length);
}
}
โ Explanation:
trim()
removes leading/trailing spaces.split("\\s+")
splits the string by one or more whitespace characters.- The length of the array gives the word count.
๐ Method 2: Count Words Using Scanner
import java.util.Scanner;
public class WordCountScanner {
public static void main(String[] args) {
String text = "Java makes software development easier";
Scanner scanner = new Scanner(text);
int count = 0;
while (scanner.hasNext()) {
scanner.next();
count++;
}
scanner.close();
System.out.println("Word count: " + count);
}
}
โ Explanation:
Scanner
treats white-space separated tokens as words.hasNext()
checks if more tokens are available.- Each
next()
represents a word.
๐งช Edge Case Handling Example
String messyText = " Multiple spaces and tabs\tare here ";
String[] words = messyText.trim().split("\\s+");
System.out.println("Word count: " + words.length);
๐ก Handles:
- Multiple spaces
- Tabs (
\t
) - Leading/trailing white space
๐ When to Use Which Method?
Method | Best For |
---|---|
split("\\s+") | Simple, fast word count |
Scanner | Token-based parsing, flexible extension |
Loop with regex | Advanced use-cases (punctuation handling, etc.) |
๐ก Tips
- โ
Always
trim()
the string to clean leading/trailing spaces. - โ ๏ธ Be cautious of empty strings or multiple consecutive spaces.
- โ
Use regular expressions (
\\s+
) to avoid splitting too strictly.
๐ Summary โ Word Count in Java
Counting words in Java is a simple yet essential task for many applications involving text processing. Whether you’re parsing input, processing text files, or analyzing user data โ this logic is a building block.
๐งพ Key Takeaways:
- Use
split("\\s+")
for reliable whitespace-based word splitting - Use
Scanner
for token-based parsing - Always
trim()
strings before splitting - Handle punctuation and special characters as needed
โFAQs โ Java Word Count
โ How does split("\\s+")
work?
It uses regex to split by one or more whitespace characters, covering spaces, tabs, and newlines.
โ Can I use this to count words in a file?
Yes! Read file content into a string using Files.readString()
or Scanner
, then apply the same logic.
โ What if the string has punctuation?
To ignore punctuation, clean the string using replaceAll("[^a-zA-Z ]", "")
.
โ Will split(" ")
work?
It works, but wonโt handle multiple spaces or tabs properly. Use split("\\s+")
instead.
Share Now :