Coders Packet

Remove all spaces from string in C++

By Sneha Gupta

Program to remove all the spaces from the string entered by the user and return it to the user

For example:

If user entered the string "How are you" then 

output - "howareyou"

In the above example, all the whitespaces are removed from the string.

C++ Code:

using namespace std;
// Function to remove all spaces from a given string
void rem(char *str)
    // To keep track of non-space character count
    int c = 0;
    /* Traverse the given string. If current character
     is not space, then place it at index 'c++'*/
    for (int i = 0; str[i]; i++)
        if (str[i] != ' ')
            str[c++] = str[i]; // here c is incremented
    str[c] = '\0';
int main()
    char str[100];
    cout<<"Enter string"<<endl;
    cin.get(str, 100);
    cout << str;
    return 0;


Download Complete Code


No comments yet