Remove spaces from std::string in C++


In this program we will see how to remove the spaces from a std::string in C++. To remove this we will use the remove() function. With this remove() function it takes the beginning and end of the iterator, then takes the third argument that will be deleted from that iterator object.

Input: A string "This is C++ Programming Language"
Output: "ThisisC++ProgrammingLanguage"

Algorithm

Step 1: Get the string
Step 2: Remove spaces from the given string using remove() function.
Step 3: Return string.

Example Code

 Live Demo

#include<iostream>
#include<algorithm>
using namespace std;
main() {
   string my_str = "This is C++ Programming Language";
   cout << "String with Spaces :" << my_str << endl;
   remove(my_str.begin(), my_str.end(), ' ');
   cout << "String without Spaces :" << my_str;
}

Output

String with Spaces :This is C++ Programming Language
String without Spaces :ThisisC++ProgrammingLanguage

Updated on: 30-Jul-2019

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements