C++ Program to Delete Spaces from String or Sentence

  • Write a C++ program to remove space characters from a string.

In this C++ program, we will remove all space characters from a string of sentence. We will not modify original string instead we will create a new string having all characters of input string except spaces.

For Example :
Input : String With  Some Space  Characters
Output : StringWithSomeSpaceCharacters

C++ Program to Remove Spaces from a String

In this program, we will first take a string input from user using cin and store it in character array input. We initialize two variable i and j to 0. Using a for loop, we will traverse input string from first character till last character and check If current character is a space character or not. It current character is not a space character then we copy it to output string otherwise skip it. After the end of for loop, we will add a null character ('\0') at the end of output string and print it on screen using cout.

//C++ Program to delete spaces from a string
#include <iostream>
#include <cstring>
using namespace std;

int main(){
    char input[100], output[100];
    int i, j;
    cout << "Enter a string \n";
    cin.getline(input, 500);
    for(i = 0, j = 0; input[i] != '\0'; i++){
        if(input[i] != ' '){
        // If current character is not a space character, 
        // copy it to output String
            output[j++] = input[i];
    output[j] = '\0';
    cout << "Input String: " << input << endl;
    cout << "String without spaces : " << output;
    return 0;
Enter a string 
I love C++ programming
Input String: I love C++ programming
String without spaces : IloveC++programming