C++ Program to Delete Spaces from String or Sentence

Here is 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.

#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;
}
Output
Enter a string 
I love C++ programming
Input String: I love C++ programming
String without spaces : IloveC++programming

Recommended Posts
C++ Program to Delete Vowels Characters from String
C++ Program to Delete a Word from Sentence
C++ Program to Count Words in Sentence
C++ Program to Convert Uppercase to Lowercase Characters
C++ Program to Copy String Without Using strcpy
C++ Program to Check whether a string is Palindrome or Not
C++ Program to Count Number of Vowels, Consonant, and Spaces in String
C++ Program to Print Pascal Triangle
C++ Program to Access Elements of an Array Using Pointer
All C++ Programs