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++

Run it Now
#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 << "\nAfter Remove Spaces :" << str;

    return 0;
}

Output:

Enter String :X i i t h
After Remove Spaces :Xiith