Java ProgramsStringsCount Spaces in a String

Count Spaces in a String in Java

beginner·  Strings  ·  String

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.

Input
Java is a powerful language
Output
Spaces: 4

Java Program

Java
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

Spaces: 4

Core Logic

A single pass through the string, comparing each character directly against a space, tallies every one found.

How It Works
  1. 1A for-each loop visits each character of the string in turn.
  2. 2c == ' ' checks whether the current character is exactly the space character.
  3. 3A match increments the count variable; anything else is skipped.
  4. 4After the loop, count holds the total number of spaces found.
For "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.

Complexity
Time Complexity: O(n)Space Complexity: O(1)

Why: Each character is visited once, and only a single running counter is kept regardless of string length.

Key Concepts

char comparisonfor-each loopcounter variable

Approach 2: Java 8

Java
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

Spaces: 4

Core Logic

The same character comparison can filter a stream of character codes down to just the spaces, then count what's left.

How It Works
  1. 1str.chars() returns an IntStream of the string's character codes.
  2. 2.filter(c -> c == ' ') keeps only the codes matching the space character.
  3. 3.count() reduces the filtered stream down to a single long total.
Filtering "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.

Complexity
Time Complexity: O(n)Space Complexity: O(1)

Why: The stream still visits every character once, and count() reduces straight down to a single long without collecting anything.

Key Concepts

Streamchars()filter()count()

Related Programs