Remove Spaces from a String in Java
The Remove Spaces problem is a simple string manipulation task where we are given a string s, and we need to remove all space characters ' ' while preserving the order of the remaining characters.
This is a common problem used to understand string traversal, filtering, and efficient string building techniques.
Problem Statement
Given a string s, remove all spaces and return the modified string.
You are not allowed to change the order of characters
Only space characters should be removed
Examples
Example 1
Input:s = "g eeks for ge eks"
Output:"geeksforgeeks"
Example 2
Input:s = "abc d "
Output:"abcd"
Key Idea
The approach is straightforward:
Iterate through the string character by character
Keep only non-space characters
Build a new result string
Since strings are immutable in Java, using StringBuilder is the most efficient approach.
Java Solution
class Solution {
String removeSpaces(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
// keep only non-space characters
if (ch != ' ') {
sb.append(ch);
}
}
return sb.toString();
}
}
How the Code Works
Step 1: Create a Result Container
StringBuilder sb = new StringBuilder();
StringBuilderis used because it allows efficient modification of stringsAvoids creating multiple string objects
Step 2: Traverse the String
for (int i = 0; i < s.length(); i++)
Loop through each character in the string
Access characters using
charAt(i)
Step 3: Filter Spaces
if (ch != ' ')
If the character is not a space → append it
If it is a space → skip it
Step 4: Build Final String
return sb.toString();
Convert the
StringBuilderinto a final stringReturn the result
Execution Example
Input:
"g eeks for ge eks"
Step-by-step processing:
g→ keep→ remove
e→ keepe→ keepk→ keeps→ keep→ remove
f→ keepo→ keepr→ keep
Final Output:
geeksforgeeks
Complexity Analysis
Time Complexity: O(n)
We traverse the string once
Auxiliary Space: O(n)
In the worst case, all characters are stored (no spaces present)
Conclusion
This problem demonstrates a fundamental string processing technique. It highlights how to efficiently filter characters while maintaining order. Using StringBuilder is crucial for performance, especially when dealing with large inputs (up to 10^5 characters).

Join the conversation! Your thoughts help the community grow.