Count Spaces in a String in Java
Problem
Counting spaces means counting how many whitespace characters — most commonly the space character — appear in a string.
Given a string, count how many space characters it contains.
Java Program
public class CountSpaces {
public static void main(String[] args) {
String str = "Java is a powerful language";
int count = 0;
for (char c : str.toCharArray()) {
if (c == ' ') count++; // counts the literal space character only
}
System.out.println("Spaces: " + count);
}
}Output
Core Logic
A single pass through the string, comparing each character directly against a space, tallies every one found.
- 1A for-each loop visits each character of the string in turn.
- 2
c == ' 'checks whether the current character is exactly the space character. - 3A match increments the
countvariable; anything else is skipped. - 4After the loop,
countholds the total number of spaces found.
"Java is a powerful language", the five words are separated by four spaces, so count ends at 4.Key Point: This checks only the literal space character — tabs or newlines wouldn't be counted, unlike Character.isWhitespace(), which treats any whitespace as a match.
Why: Each character is visited once, and only a single running counter is kept regardless of string length.
Key Concepts
Approach 2: Java 8
public class CountSpacesStream {
public static void main(String[] args) {
String str = "Java is a powerful language";
// filter() keeps only the space character codes; count() reduces to a single total
long count = str.chars().filter(c -> c == ' ').count();
System.out.println("Spaces: " + count);
}
}
Output
Core Logic
The same character comparison can filter a stream of character codes down to just the spaces, then count what's left.
- 1
str.chars()returns anIntStreamof the string's character codes. - 2
.filter(c -> c == ' ')keeps only the codes matching the space character. - 3
.count()reduces the filtered stream down to a singlelongtotal.
"Java is a powerful language" keeps only the four space characters, so count() returns 4.Key Point: Swapping the lambda to Character::isWhitespace instead of c == ' ' would extend this to catch tabs and newlines too, the same trade-off the loop version has.
Why: The stream still visits every character once, and count() reduces straight down to a single long without collecting anything.