Remove spaces from a given string

Last Updated : 11 Apr, 2026

Given a string s, remove all spaces from the string and return it. 

Examples:

Input: s = "g eeks for ge eeks "
Output: geeksforgeeks
Explanation: All the spaces have been removed.

Input: s = " abc d "
Output: abcd
Explanation: All the spaces including the leading ones have been removed.

Try It Yourself
redirect icon

[Naive Approach] Using Brute Force - O(n*n) Time and O(1) Space

Traverse the string and whenever a space is found, shift all the following characters one position to the left and reduce the effective length of the string.

Dry run for s = " gf g":

  1. Initialize n = 5 (length of the string).
  2. For i = 0, ' ' is space then shift all characters left so, string becomes "gf g" and reduce n to 4, decrement i.
  3. For i = 0, 'g' is not space then move to next index.
  4. For i = 1, 'f' is not space then move to next index.
  5. For i = 2, ' ' is space then shift all characters left so, string becomes "gfg" and reduce n to 3, decrement i.
  6. For i = 2, 'g' is not space then move to next index.
  7. Traversal complete, return substring s[0 to n-1].
C++
#include <iostream>
#include <string>
using namespace std;

string removeSpaces(string& s) {
    int n = s.length();

    for (int i = 0; i < n; i++) {
        if (s[i] == ' ') {

            // shift all characters to the left
            // starting from current index
            for (int j = i; j < n - 1; j++) {
                s[j] = s[j + 1];
            }
            n--;    
            i--;   
        }
    }

    // return string up to new valid length
    // without spaces
    return s.substr(0, n);
}

int main() {
    string s = "g  eeks   for ge  eeks  ";
    cout << removeSpaces(s);
    return 0;
}
C
#include <stdio.h>
#include <string.h>

char* removeSpaces(char s[]) {
    int n = strlen(s);

    for (int i = 0; i < n; i++) {
        if (s[i] == ' ') {

            // shift all characters to the left
            // starting from current index
            for (int j = i; j < n - 1; j++) {
                s[j] = s[j + 1];
            }
            n--;
            i--;
        }
    }

    // return string up to new valid length
    // without spaces
    s[n] = '\0';  
    return s;
}

int main() {
    char s[] = "g  eeks   for ge  eeks  ";
    printf("%s", removeSpaces(s));
    return 0;
}
Java
class GfG {

    static String removeSpaces(String s) {
        char[] arr = s.toCharArray();
        int n = arr.length;
    
        for (int i = 0; i < n; i++) {
            if (arr[i] == ' ') {
    
                // shift all characters to the left
                // starting from current index
                for (int j = i; j < n - 1; j++) {
                    arr[j] = arr[j + 1];
                }
                n--;
                i--;
            }
        }
    
        // return string up to new valid length
        // without spaces
        return new String(arr, 0, n); 
    }

    public static void main(String[] args) {
        String s = "g  eeks   for ge  eeks  ";
        System.out.print(removeSpaces(s));
    }
}
Python
def removeSpaces(s):
    
    # convert to list 
    # (strings are immutable in Python)
    s = list(s)
    n = len(s)
    i = 0

    while i < n:
        if s[i] == ' ':

            # shift all characters to the left
            # starting from current index
            for j in range(i, n - 1):
                s[j] = s[j + 1]
            n -= 1
            i -= 1
        i += 1

    # return string up to new valid length
    # without spaces
    return "".join(s[:n])


if __name__ == "__main__":
    s = "g  eeks   for ge  eeks  "
    print(removeSpaces(s))
C#
using System;

class GfG {

    static string removeSpaces(string s) {
        char[] arr = s.ToCharArray();
        int n = arr.Length;
    
        for (int i = 0; i < n; i++) {
            if (arr[i] == ' ') {
    
                // shift all characters to the left
                // starting from current index
                for (int j = i; j < n - 1; j++) {
                    arr[j] = arr[j + 1];
                }
                n--;
                i--;
            }
        }
    
        // return string up to new valid length
        // without spaces
        return new string(arr, 0, n);
    }

    static void Main() {
        string s = "g  eeks   for ge  eeks  ";
        Console.Write(removeSpaces(s));
    }
}
JavaScript
function removeSpaces(s) {
    s = s.split('');
    let n = s.length;

    for (let i = 0; i < n; i++) {
        if (s[i] === ' ') {

            // shift all characters to the left
            // starting from current index
            for (let j = i; j < n - 1; j++) {
                s[j] = s[j + 1];
            }
            n--;
            i--;
        }
    }

    // return string up to new valid length
    // without spaces
    return s.slice(0, n).join("");
}

// Driver code
let s = "g  eeks   for ge  eeks  ";
console.log(removeSpaces(s));

Output
geeksforgeeeks

[Expected Approach] Using Two Pointer - O(n) Time and O(1) Space

Traverse the string using two indices, where one index reads each character and the other writes only non-space characters. Whenever a non-space character is found, place it at the write index and move both pointers accordingly. This way, all non-space characters are shifted forward without using extra space.

Dry run for s = "gf g":

  1. Initialize two pointers i = 0, itr = 0
  2. For i = 0, 'g' is not space then copy to s[itr], increment itr to 1
  3. For i = 1, 'f' is not space then copy to s[1], itr to 2
  4. For i = 2, ' ' is space then skip, only i moves
  5. For i = 3, ' ' is space then skip
  6. For i = 4, 'g' is not space then copy to s[2], itr to 3
  7. Traversal complete, return substring s[0 to itr-1]
C++
#include <iostream>
#include <string>
using namespace std;

string removeSpaces(string& s) {
    int n = s.length();
    int i = 0, itr = 0;

    // Iterate through the string
    while (i < n) {
        
        // Check if current character 
        // is not a space
        if (s[i] != ' '){
            
            // Copy the non-space character 
            // to the new string
            s[itr++] = s[i];
        }
        i++;
    }

    // Return only the modified part of the string 
    // without any extra characters
    return s.substr(0, itr);
}

int main() {
    string s = "g  eeks   for ge  eeks  ";
    cout << removeSpaces(s);
    return 0;
}
C
#include <stdio.h>
#include <string.h>

char* removeSpaces(char s[]) {
    int n = strlen(s);
    int i = 0, itr = 0;

    // Iterate through the string
    while (i < n) {
        
        // Check if current character 
        // is not a space
        if (s[i] != ' ') {
            
            // Copy the non-space character 
            // to the new string
            s[itr++] = s[i];
        }
        i++;
    }

    // add null character to mark end of string
    s[itr] = '\0';

    // Return only the modified part of the string 
    // without any extra characters
    return s;
}

int main() {
    char s[] = "g  eeks   for ge  eeks  ";
    printf("%s", removeSpaces(s));
    return 0;
}
Java
class GfG {

    static String removeSpaces(String s) {
        int n = s.length();
        int i = 0, itr = 0;
    
        // convert string to character array
        char[] arr = s.toCharArray();
    
        // Iterate through the string
        while (i < n) {
            
            // Check if current character 
            // is not a space
            if (arr[i] != ' ') {
                
                // Copy the non-space character 
                // to the new string
                arr[itr++] = arr[i];
            }
            i++;
        }
    
        // Return only the modified part of the string 
        // without any extra characters
        return new String(arr, 0, itr);
    }

    public static void main(String[] args) {
        String s = "g  eeks   for ge  eeks  ";
        System.out.print(removeSpaces(s));
    }
}
Python
def removeSpaces(s):
    n = len(s)
    i = 0
    itr = 0

    # convert to list 
    # (strings are immutable in Python)
    s = list(s)

    # Iterate through the string
    while i < n:
        
        # Check if current character 
        # is not a space
        if s[i] != ' ':
            
            # Copy the non-space character 
            # to the new string
            s[itr] = s[i]
            itr += 1
        i += 1

    # Return only the modified part of the string 
    # without any extra characters
    return "".join(s[:itr])


if __name__ == "__main__":
    s = "g  eeks   for ge  eeks  "
    print(removeSpaces(s))
C#
using System;

class GfG {

    static string removeSpaces(string s) {
        int n = s.Length;
        int i = 0, itr = 0;
    
        // convert string to character array
        char[] arr = s.ToCharArray();
    
        // Iterate through the string
        while (i < n) {
            
            // Check if current character 
            // is not a space
            if (arr[i] != ' ') {
                
                // Copy the non-space character 
                // to the new string
                arr[itr++] = arr[i];
            }
            i++;
        }
    
        // Return only the modified part of the string 
        // without any extra characters
        return new string(arr, 0, itr);
    }

    static void Main() {
        string s = "g  eeks   for ge  eeks  ";
        Console.Write(removeSpaces(s));
    }
}
JavaScript
function removeSpaces(s) {
    let n = s.length;
    let i = 0, itr = 0;

    // convert string to character array
    let arr = s.split('');

    // Iterate through the string
    while (i < n) {
        
        // Check if current character 
        // is not a space
        if (arr[i] !== ' ') {
            
            // Copy the non-space character 
            // to the new string
            arr[itr++] = arr[i];
        }
        i++;
    }

    // Return only the modified part of the string 
    // without any extra characters
    return arr.slice(0, itr).join("");
}

// Driver code
let s = "g  eeks   for ge  eeks  ";
console.log(removeSpaces(s));

Output
geeksforgeeeks

Using Built-in functions - O(n) Time and O(1) Space

Use a built-in string function to remove or skip all space characters while forming the result. This processes each character once and returns a new string without spaces in linear time.

C++
#include <iostream>
#include <algorithm>
using namespace std;

string removeSpaces(string& s) {
    
    // move non-space characters to front
    auto new_end = remove(s.begin(), s.end(), ' ');
    
    // erase extra part
    s.erase(new_end, s.end());
    
    return s;
}

int main() {
    string s = "g  eeks   for ge  eeks  ";
    cout << removeSpaces(s);
    return 0;
}
Java
public class GfG {

    static String removeSpaces(String s) {
        
        // replace all spaces with empty string
        s = s.replace(" ", "");
        return s;
    }

    public static void main(String[] args) {
        String s = "g  eeks   for ge  eeks  ";
        System.out.print(removeSpaces(s));
    }
}
Python
def removeSpaces(s):
    
    s = s.replace(" ", "")
    return s

if __name__ == "__main__":
    s = "g  eeks   for ge  eeks  "
    print(removeSpaces(s), end="")
C#
using System;

class GfG {

    static string RemoveSpaces(string s) {
        
        // replace all spaces with empty string
        s = s.Replace(" ", "");
        return s;
    }

    static void Main() {
        string s = "g  eeks   for ge  eeks  ";
        Console.Write(RemoveSpaces(s));
    }
}
JavaScript
function removeSpaces(s) {
    
    // replace all spaces with empty string
    return s.replace(/ /g, "");
}

// Driver code
let s = "g  eeks   for ge  eeks  ";
console.log(removeSpaces(s));

Output
geeksforgeeeks

Note: C does not have a built-in function to remove spaces, so it must be done manually.

Comment