Count Words in a Sentence in Java — Definition, Examples and Program
Counting words in a sentence is a common string problem. It helps in text analysis, document processing, and input validation.
In this blog, you will learn:
- What a word is
- How to count words correctly
- Step-by-step examples
- A Java program
- Practice challenges
What Is a Word?
A word is a group of characters separated by spaces. Multiple spaces between words should not be counted as extra words.
How the Logic Works
To count words in a sentence:
- Ignore leading and trailing spaces.
- Count transitions from space to non-space characters.
- Each transition indicates the start of a new word.
Example 1
Input: "Java is fun"
- Words: Java, is, fun
Total Words: 3
Example 2
Input: " Learn Java Programming "
- Extra spaces are ignored
- Words: Learn, Java, Programming
Total Words: 3
Java Program to Count Words
import java.util.Scanner;
public class CountWords {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String sentence = sc.nextLine();
int wordCount = 0;
boolean isWord = false;
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
if (ch != ' ' && !isWord) {
wordCount++;
isWord = true;
} else if (ch == ' ') {
isWord = false;
}
}
System.out.println("Number of words: " + wordCount);
}
}
Sample Output
Enter a sentence: Java programming is powerful
Number of words: 4
Practice Challenges
- Count words without using any extra boolean variable.
- Count words using split() and compare both approaches.
- Find the longest word in a sentence.
Counting words accurately requires careful handling of spaces. This problem builds strong fundamentals in string traversal and condition handling.