C++ Program to remove spaces from a string


In this program, You will learn how to remove spaces from a string in C++.


String is: J o h n S m i t h

After remove spaces: JohnSmith

Example: How to remove spaces from a string in C++.

#include<iostream>
#include<cstring>
using namespace std;

int main() {

    char str[100];
    int i, j = 0, k, size;

    cout << "Enter string:";
    cin.getline(str, 100);

    size = strlen(str);
    for (i = 0; i < size; i++) {
        if (str[i] != ' ') {
            str[j] = str[i];
            j++;
        }
    }

    str[j] = '\0';
    cout << "After remove spaces:" << str;

    return 0;
}

Output:

Enter string:Xiith com
After remove spaces:Xiithcom