C++ Program to Remove Spaces from a String

«
»

This is a C++ Program to Remove the Spaces in a String.

Problem Description

The program takes a string and removes the spaces in it.

Problem Solution

1. The program takes a string.
2. Using a for loop, any spaces found in the string are removed.
3. The result is printed.
4. Exit.

C++ Program/Source code

Here is the source code of C++ Program to Remove the Spaces in a String. The program output is shown below.

  1. #include<iostream>
  2. #include<string.h>
  3. using namespace std;
  4. int main ()
  5. {   char str[80];
  6.     int i=0, len, j;
  7.     cout << "Enter a string : ";
  8.     gets(str);
  9.     len = strlen(str);
  10.     for( i = 0; i < len; i++)
  11.     {
  12.         if (str[i] == ' ')
  13.         {
  14.             for (j = i; j < len; j++)
  15.                 str[j] = str[j+1];
  16.             len--;
  17.         }
  18.     }
  19.     cout << "Resultant string : " << str;
  20.     return 0;
  21. }
Program Explanation

1. The program takes a string and stores it in ‘str’.
2. Using a for loop, if a space is encountered it is removed by shifting elements to the left.
3. The resultant string is printed.

Note: Join free Sanfoundry classes at Telegram or Youtube
advertisement
advertisement
Runtime Test Cases
Case 1 :
Enter a string : A B C D E
Resultant string : ABCDE
 
Case 2 :
Enter a string : B a l l 2 5
Resultant string : Ball25
 
Case 3 :
Enter a string : Welcome to Programming World!
Resultant string : WelcometoProgrammingWorld!

Sanfoundry Global Education & Learning Series – C++ Programs.

To practice all C++ programs, here is complete set of 1000+ C++ Programming examples.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.