Back to Strings
Q31Question 31 of 61

Remove All Spaces from a String

Key Concepts
  • Java strings are immutable, so build the result in a StringBuilder by appending only non-space characters.
  • Decide whether to remove only ASCII spaces or all whitespace including tabs, newlines, and carriage returns using Character.isWhitespace().
  • Pre-size the StringBuilder to the input length to avoid repeated internal array growth on large strings.
  • Trimming removes only leading and trailing whitespace, while full removal deletes every space anywhere in the string.
  • String.replace(' ', '') removes only ASCII spaces; String.replaceAll("\\s", "") removes all whitespace but recompiles the pattern each call.
  • For high-volume batch processing, pre-compile the regex pattern or use the explicit loop for better performance.

Definition

Build a new string with a StringBuilder, appending only non-space characters, since strings cannot be edited in place.
  • StringBuilder loop iterates over every character and appends only those that are not spaces, producing a clean result in O(n) time.
  • Immutability constraint means you cannot delete characters from an existing Java string; you must build a new one.
  • Whitespace scope determines whether you strip only ASCII spaces or all whitespace including tabs and newlines via Character.isWhitespace().
  • Pre-sizing the StringBuilder to the input length avoids internal array resizing during the append loop.
  • Trim vs remove is an important distinction: trim() strips only leading and trailing whitespace, while full removal deletes every whitespace character anywhere.

When Priya pastes her account number from an email into the National Bank of India app, the number comes with spaces for readability like "2001 4500 7890". Before the system can look it up, those spaces must be scrubbed out so the number becomes one clean token "200145007890". The system walks through the text and copies only the real characters, skipping every space.

Understanding the Concepts

What does removing all spaces mean?

Removing all spaces from a string produces a new string that keeps every non-space character in its original order while dropping every space character. In Java, strings are immutable, so you cannot modify the original. You create a new result by iterating over each character and appending only the ones that are not spaces.

JAVA
package com.bank.util;

public class SpaceRemover {
    public static String removeAllSpaces(String input) {
        if (input == null) return null;
        StringBuilder sb = new StringBuilder(input.length());
        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c != ' ') {
                sb.append(c);
            }
        }
        return sb.toString();
    }
}

Why does this matter in banking?

Customers paste account numbers, IFSC codes, and PAN numbers from emails, PDFs, and statements. These pasted values carry hidden spaces, tabs, and sometimes newline characters. A database lookup on "2001 4500" fails even though the human-readable number matches "200145007890". Rajesh at the National Bank of India runs this cleaning step before storage and before any matching query.

JAVA
package com.bank.service;

import com.bank.util.SpaceRemover;

public class AccountLookupService {
    public String cleanAndLookup(String rawAccountNumber) {
        String cleaned = SpaceRemover.removeAllSpaces(rawAccountNumber);
        System.out.println("Looking up: '" + cleaned + "'");
        // perform database lookup with cleaned value
        return cleaned;
    }

    public static void main(String[] args) {
        AccountLookupService service = new AccountLookupService();
        service.cleanAndLookup("2001 4500 7890");
    }
}
TEXT
Looking up: '200145007890'

How do you remove all whitespace, not just spaces?

The ASCII space character is just one kind of whitespace. Tabs, newlines, and carriage returns are also whitespace. When a customer copies from a spreadsheet, the pasted text may contain tabs. Use Character.isWhitespace() to catch all of them.

JAVA
package com.bank.util;

public class WhitespaceRemover {
    public static String removeAllWhitespace(String input) {
        if (input == null) return null;
        StringBuilder sb = new StringBuilder(input.length());
        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (!Character.isWhitespace(c)) {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        String pasted = "2001\t4500\n7890";
        System.out.println("Before: '" + pasted.replace("\t", "[TAB]").replace("\n", "[NL]") + "'");
        System.out.println("After:  '" + removeAllWhitespace(pasted) + "'");
    }
}
TEXT
Before: '2001[TAB]4500[NL]7890'
After:  '200145007890'

How is trim() different from removing all spaces?

The trim() method removes only leading and trailing whitespace. It leaves spaces inside the string untouched. For a display name like " Priya Sharma ", trimming produces "Priya Sharma" which is correct. But for an account number like " 2001 4500 ", trimming produces "2001 4500" which still has the inner space. Full removal is needed for identifiers.

JAVA
package com.bank.util;

public class TrimVsRemoveDemo {
    public static void main(String[] args) {
        String name = "  Priya Sharma  ";
        String account = "  2001 4500  ";

        System.out.println("Name trimmed:    '" + name.trim() + "'");
        System.out.println("Account trimmed: '" + account.trim() + "'");
        System.out.println("Account cleaned: '" + WhitespaceRemover.removeAllWhitespace(account) + "'");
    }
}
TEXT
Name trimmed:    'Priya Sharma'
Account trimmed: '2001 4500'
Account cleaned: '20014500'

What are the alternative approaches?

Java provides several built-in methods. String.replace(" ", "") removes only ASCII spaces. String.replaceAll("\\s", "") removes all whitespace using a regex but recompiles the pattern on every call. For hot paths, pre-compile the pattern.

JAVA
package com.bank.util;

import java.util.regex.Pattern;

public class AlternativeApproaches {
    private static final Pattern WHITESPACE = Pattern.compile("\\s");

    public static void main(String[] args) {
        String input = "2001 4500\t7890";

        // Approach 1: replace only ASCII space
        System.out.println(input.replace(" ", ""));         // "20014500\t7890" (tab stays)

        // Approach 2: replaceAll with regex (recompiles each call)
        System.out.println(input.replaceAll("\\s", ""));    // "200145007890"

        // Approach 3: pre-compiled pattern (best for hot paths)
        System.out.println(WHITESPACE.matcher(input).replaceAll("")); // "200145007890"
    }
}
TEXT
20014500	7890
200145007890
200145007890

What are the edge cases?

Null input should return null or throw, depending on convention. An empty string returns an empty string. A string of all spaces returns an empty string. A string with no spaces at all returns itself unchanged.

JAVA
package com.bank.util;

public class EdgeCaseDemo {
    public static void main(String[] args) {
        System.out.println("null:       " + SpaceRemover.removeAllSpaces(null));
        System.out.println("empty:      '" + SpaceRemover.removeAllSpaces("") + "'");
        System.out.println("all spaces: '" + SpaceRemover.removeAllSpaces("   ") + "'");
        System.out.println("no spaces:  '" + SpaceRemover.removeAllSpaces("200145") + "'");
    }
}
TEXT
null:       null
empty:      ''
all spaces: ''
no spaces:  '200145'

What are common mistakes?

The first mistake is using replace when all whitespace needs removal, since replace(" ", "") leaves tabs and newlines. The second mistake is not pre-sizing the StringBuilder, causing repeated internal array growth on large strings. The third mistake is confusing trim() with full removal.

JAVA
package com.bank.util;

public class CommonMistakesDemo {
    public static void main(String[] args) {
        String input = " 2001\t4500 ";

        // WRONG: replace only removes ASCII space, tab stays
        String wrong = input.replace(" ", "");
        System.out.println("Wrong: '" + wrong + "' (tab still present)");

        // CORRECT: remove all whitespace
        String correct = WhitespaceRemover.removeAllWhitespace(input);
        System.out.println("Correct: '" + correct + "'");
    }
}
TEXT
Wrong: '2001	4500' (tab still present)
Correct: '20014500'

What is the time and space complexity?

The loop runs in O(n) time where n is the length of the input string. It uses O(n) extra space for the StringBuilder. Pre-sizing the StringBuilder to the input length avoids internal array resizing, which matters for bulk import of millions of account identifiers at the National Bank of India.

JAVA
package com.bank.util;

public class PerformanceDemo {
    public static void main(String[] args) {
        // Pre-sized StringBuilder avoids resizing
        String large = "1234 5678 ".repeat(100_000);
        long start = System.nanoTime();
        String result = WhitespaceRemover.removeAllWhitespace(large);
        long elapsed = System.nanoTime() - start;
        System.out.println("Length: " + result.length() + ", Time: " + elapsed / 1_000_000 + "ms");
    }
}

What are common interview follow-up questions?

  • How would you remove only duplicate spaces, keeping single spaces between words?
  • How would you replace multiple consecutive spaces with a single space?
  • What is the difference between trim(), strip() (Java 11), and removing all spaces?
  • How would you handle Unicode whitespace characters like non-breaking space?

Visual Overview

DIAGRAM
  Input: "2001 4500 7890"
       │
       ▼
  ┌─────────────────────────────────┐
  │  StringBuilder sb (pre-sized)    │
  └─────────────────────────────────┘
       │
  i=0  '2' ── not space ── append ── sb: "2"
  i=1  '0' ── not space ── append ── sb: "20"
  i=2  '0' ── not space ── append ── sb: "200"
  i=3  '1' ── not space ── append ── sb: "2001"
  i=4  ' ' ── SPACE ────── skip
  i=5  '4' ── not space ── append ── sb: "20014"
  i=6  '5' ── not space ── append ── sb: "200145"
  i=7  '0' ── not space ── append ── sb: "2001450"
  i=8  '0' ── not space ── append ── sb: "20014500"
  i=9  ' ' ── SPACE ────── skip
  i=10 '7' ── not space ── append ── sb: "200145007"
  i=11 '8' ── not space ── append ── sb: "2001450078"
  i=12 '9' ── not space ── append ── sb: "20014500789"
  i=13 '0' ── not space ── append ── sb: "200145007890"
       │
       ▼
  Output: "200145007890"

Key Takeaway

Removing all spaces from a string in Java means building a new string, because Java strings are immutable and cannot be edited in place. Rajesh at the National Bank of India creates a StringBuilder pre-sized to the input length, loops over every character, and appends only the characters that are not spaces. The result is a clean token with no gaps, ready for database lookup or downstream processing.

The key decision is what counts as a space. If you only want to drop the plain ASCII space, compare against the space character directly or use String.replace. If you want to drop every kind of whitespace including tabs and newlines that customers paste from spreadsheets and emails, use Character.isWhitespace() which recognizes all of them. For banking identifiers, Priya's pasted account numbers often carry hidden tabs and carriage returns, so the whitespace-aware version is the safe default.

The distinction between trimming and removing all spaces is important. Trimming with trim() or strip() removes only leading and trailing whitespace and keeps inner spaces intact, which is correct for display names like "Priya Sharma". Full removal deletes every space anywhere, which is correct for account numbers and IFSC codes where no gaps are allowed.

For high-volume batch processing of millions of account identifiers, the explicit StringBuilder loop with pre-sizing outperforms the regex alternative. If you do use a regex, pre-compile the pattern once with Pattern.compile("\\s") and reuse the compiled pattern rather than calling replaceAll which recompiles on every invocation.

Remember one sentence: build a new string with StringBuilder by appending only non-whitespace characters, and choose between ASCII-space-only and all-whitespace removal based on what the field actually needs.

---

Share
Use ← → arrow keys to navigate