Skip to content
Related Articles

Related Articles

C++ Program to remove spaces from a string

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 26 Oct, 2022
Improve Article
Save Article

Given a string, remove all spaces from it. For example “g e e k” should be converted to “geek” and ” g e ” should be converted to “ge”. The idea is to traverse the string from left to right and ignore spaces while traversing. We need to keep track of two indexes, one for current character being red and other for current index in output. 

Implementation:

C++




// C++ program to evaluate a given expression
#include <iostream>
using namespace std;
 
char *removeSpaces(char *str)
{
    int i = 0, j = 0;
    while (str[i])
    {
        if (str[i] != ' ')
        str[j++] = str[i];
        i++;
    }
    str[j] = '\0';
    return str;
}
 
// Driver program to test above function
int main()
{
    char str1[] = "gee k ";
    cout << removeSpaces(str1) << endl;
 
    char str2[] = " g e e k ";
    cout << removeSpaces(str2);
    return 0;
}


Output

geek
geek

Time complexity: O(n) where n is number of characters in input string.
Auxiliary Space: O(1)

Approach 2: using in-built function

Main idea in this approach is we will traverse the whole string and will delete the space by using in-built erase function from C++ STL.

Time complexity will be O(N) where N is length of string and the solution will also be in-place solution.

C++




//C++ program to remove spaces from
//string using in-built function
#include <bits/stdc++.h>
using namespace std;
 
//function to remove the spaces from string
void removespace(string s)
{
    //traversing the string
    for (int i = 0; i < s.length(); i++)
    {
        if (s[i] == ' ')
        {
            //using in-built function to erase element
            s.erase(s.begin() + i);
            i--;
        }
    }
    cout << s;
}
 
int main()
{
    string s = "Gee k ";
    cout << "original string is: " <<s<<endl;
    cout << "final updated string: ";
    //function calling
    removespace(s);
    cout<<endl;
    string s1="G e e k";
    cout << "original string is: " <<s1<<endl;
    cout << "final updated string: ";
    //function calling
    removespace(s1);
    return 0;
}
//this code is contributed by machhaliya muhammad


Output

original string is: Gee k 
final updated string: Geek
original string is: G e e k
final updated string: Geek

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!