How to ignore spaces in c++ – C++ Program to Delete Spaces from String or Sentence

How to ignore spaces in c++: In the previous article, we have discussed C++ Program to Print Array in Reverse Order. In this article, we will see C++ Program to Delete Spaces from String or Sentence.

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

C++ remove all spaces from 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 Remove Spaces from a String

//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;
}

Output

Enter a string 
I love C++ programming
Input String: I love C++ programming
String without spaces : IloveC++programming

The comprehensive list of C++ Programs Examples covered in our pages are very useful for every beginners and experienced programmers. So, make use of these C++ Coding Exercises & hold a grip on the programming language.