Count Spaces in a String in Java — Definition, Examples and Program

Learn how to count spaces in a string using Java. This blog explains the concept with examples, a simple Java program, and practice challenges for beginners.

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 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:

  1. Read the input string.
  2. Traverse each character of the string.
  3. Check whether the character is a space (' ').
  4. Increase the space count when a space is found.

Example 1

Input: "Java is fun"

Total Spaces: 2

Example 2

Input: " Count spaces "

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

  1. Modify the program to count words in a string.
  2. Ignore leading and trailing spaces while counting.
  3. 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.