TechByteByByte

Count Non-Space Characters in a String - Java

An easy QA/automation coding interview question: count Non-Space Characters in a String, with a full Java walkthrough, dry run, and common interviewer follow-ups.

#Strings#Loops#Easy#Java

Category: Easy | Concepts used: String iteration, character checks, Unicode whitespace detection


Problem Statement

Given a string, count how many characters are not whitespace (spaces, tabs, newlines, line breaks).

Input : "Hello World"     Output: 10   (11 characters total - 1 space)
Input : "   "              Output: 0    (all spaces)

Examples (with edge scenarios)

#InputOutputWhy
1"Hello World"1011 total characters, 1 space
2"" (empty)0Nothing to count
3" " (only spaces)0All characters are spaces
4"a b c"33 letters, 2 spaces
5"Hi\tThere"7Tab (\t) counts as whitespace

โš ๏ธ Common Beginner Mistake

MistakeImpactFix
Checking only plain spaces (ch == ' ')Fails to detect tabs (\t) and line feeds (\n)Use Character.isWhitespace(ch)
Returning str.length() directlyCounts space characters as lettersLoop and selectively count only non-whitespace characters

Before You Code: Clarify the Contract

Before choosing an algorithm, confirm how null and empty strings should behave, whether comparison is case-sensitive, and whether spaces or punctuation count. Java char values are UTF-16 code units, not always complete human-visible Unicode characters, so international text may require code points or grapheme-aware libraries.

Analogy: Counting Apples in Packing Peanuts

Imagine you receive a package containing apples (visible characters) packed in foam packing peanuts (whitespace characters).

  • To find out how many apples you got, you reach into the box and count them.
  • As you unpack, you ignore the peanuts, cardboard inserts, and paper stuffing (various forms of whitespace).
  • Every time your hand touches a real, solid apple, you count it. Your final count is the total number of apples, ignoring the packing material!

Solution 1 โ€” Loop + Manual Space Check (Basic)

This solution counts characters that are not equal to the plain space character ' '.

Intuition

Walk through the string character by character. If a character is not equal to ' ', increment our counter.

public class CountNonSpace {
    public static int countNonSpace(String str) {
        if (str == null || str.isEmpty()) {
            return 0;
        }

int count = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) != ' ') { // Only checks plain space ' '
                count++;
            }
        }
        return count;
    }

public static void main(String[] args) {
        System.out.println(countNonSpace("Hello World")); // 10
        System.out.println(countNonSpace("   "));          // 0
        System.out.println(countNonSpace(""));              // 0
    }
}

Output:

10
0
0

Dry Run (str = โ€œa bโ€)

i = 0: 'a' != ' ' -> count = 1
i = 1: ' ' == ' ' -> skip
i = 2: 'b' != ' ' -> count = 2
Final count = 2

Solution 2 โ€” Using Character.isWhitespace() (Handles All Whitespace)

This is the preferred solution as it handles all standard whitespace characters (tabs, newlines, vertical tabs, Unicode spaces).

Intuition

Whitespace isnโ€™t just the spacebar character. We delegate whitespace detection to Character.isWhitespace(), which handles tabs (\t), newlines (\n), carriage returns (\r), and more.

public class CountNonSpaceWhitespace {
    public static int countNonSpace(String str) {
        if (str == null || str.isEmpty()) {
            return 0;
        }

int count = 0;
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (!Character.isWhitespace(ch)) { // Checks space, tab, newline, carriage return, etc.
                count++;
            }
        }
        return count;
    }

public static void main(String[] args) {
        System.out.println(countNonSpace("Hi\tThere"));   // 7
        System.out.println(countNonSpace("Hello World")); // 10
    }
}

Output:

7
10

๐Ÿ“Š Visual Flowchart

graph TD
    Start["Given String S"] --> Empty{"S is null or empty?"}
    Empty -->|Yes| RetZero["Return 0"]
    Empty -->|No| InitCount["Initialize count = 0"]
    InitCount --> Loop{"i < S.length()?"}
    Loop -->|Yes| Fetch["ch = S.charAt(i)"]
    Fetch --> Check{"Character.isWhitespace(ch)?"}
    Check -->|Yes| IncLoop["i++"]
    Check -->|No| IncCount["count++"]
    IncCount --> IncLoop
    IncLoop --> Loop
    Loop -->|No| End["Return count"]

Interviewer Insights

This question determines if you consider real-world formatting characters beyond basic spacebars.

Follow-up questions you might get:

  • โ€œWhat about using replaceAll() to solve this in one line?โ€ โ†’ You can write:
    public static int countNonSpaceOneLiner(String str) {
        if (str == null) return 0;
        return str.replaceAll("\\s", "").length();
    }
    Interview Tip: Proactively explain the trade-offs of this one-liner. While itโ€™s concise, replaceAll() uses Regular Expressions (slower CPU-wise) and internally creates a brand-new string in memory, taking (O(N)) auxiliary space. The loop-based solution is much more memory efficient, operating in (O(1)) auxiliary space.
  • โ€œWhy is Character.isWhitespace() better than checking a list of chars manually?โ€ โ†’ It supports Unicode whitespace characters (like the non-breaking space \u00A0 or Ogham space mark), making the software internationalization-ready.

Quick Recap

ApproachHandles tabs/newlines?Space Complexity (Auxiliary)Time ComplexityInterview Signal
Manual ' ' checkNo(O(1))(O(N))Basic string traversal
Character.isWhitespace()Yes(O(1))(O(N))Industry-standard, Unicode-compliant, robust
Regex (replaceAll)Yes(O(N))(O(N))Concise, but memory-intensive
Author
TechByteByByte Editorial Team
Reviewed by
TechByteByByte Admin
Published
Last reviewed