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.
#include<iostream>
#include<string.h>
using namespace std;
int main ()
{ char str[80];
int i=0, len, j;
cout << "Enter a string : ";
gets(str);
len = strlen(str);
for( i = 0; i < len; i++)
{
if (str[i] == ' ')
{
for (j = i; j < len; j++)
str[j] = str[j+1];
len--;
}
}
cout << "Resultant string : " << str;
return 0;
}
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.
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.
Related Posts:
- Practice Computer Science MCQs
- Check C++ Books
- Apply for C++ Internship
- Check Programming Books
- Apply for Computer Science Internship