C++ Program to remove spaces from a string

In this article, you will learn a C++ Program to remove spaces from a string. Sometimes the programmer wants to remove spaces from the string. This program is very useful for that time.

For example, if we have a string “Hello World” the program displays it as “HelloWorld”.

Example 1: Remove spaces from a string in C++

In this C++ program, the user asks to enter the string with spaces. The program begins to check spaces, if the space is found it replaces it with the next character just after the space.

This process continues until the whole string will be checked. After computation, the resultant string without spaces displays on the console screen.

#include <iostream>
#include<string.h>
using namespace std;
int main(){
   char str[100];
   int strlength;
   cout<<"Enter the String: ";
    gets(str);
   strlength = strlen(str);
   for(int i = 0; i < strlength; i++) {
      if (str[i] == ' ') {
         for (int j = i; j < strlength; j++)
            str[j] = str[j+1];
            strlength--;
      }
   }
   cout << str;
   return 0;
}

Output 1

Enter the String: Hello World
HelloWorld

Output 2

Enter the String: Logic to program
Logictoprogram

Recommended Articles

C++ program to check prime numbers

C++ program to check even odd number

Scroll to Top