Count Spaces in a String in Java — Definition, Examples and Program
Counting spaces in a string is a simple yet useful string problem. It helps in analyzing sentences, validating inputs, and processing text data.
In this blog, you will learn:
- What spaces are in a string
- How to count spaces
- Step-by-step examples
- A simple Java program
- Practice challenges
What Are Spaces?
A space is the blank character between words in a sentence. In Java, it is represented by the character ' '.
How the Logic Works
To count spaces in a string:
- Read the input string.
- Traverse each character of the string.
- Check whether the character is a space (' ').
- Increase the space count when a space is found.
Example 1
Input: "Java is fun"
- Spaces between words: 2
Total Spaces: 2
Example 2
Input: " Count spaces "
- Leading space → 1
- Multiple spaces between words → 3
- Trailing space → 1
Total Spaces: 5
Java Program to Count Spaces
import java.util.Scanner;
public class CountSpaces {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = sc.nextLine();
int spaceCount = 0;
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == ' ') {
spaceCount++;
}
}
System.out.println("Number of spaces: " + spaceCount);
}
}
Sample Output
Enter a string: Java programming is easy
Number of spaces: 3
Practice Challenges
- Modify the program to count words in a string.
- Ignore leading and trailing spaces while counting.
- Replace multiple spaces with a single space.
Counting spaces is a foundational string operation and helps build a strong understanding of text processing in Java.