Removing white spaces from a string in C++

Tags:

Removing white spaces from a string in C++

#include <iostream>

using namespace std;

int main (int argc, char *argv[])
{
  string s (“ab cd ef”);

  s.erase ( remove(s.begin (), s.end (), ‘ ‘), s.end ());
  cout << “[“ << s << “]” << endl;

  return EXIT_SUCCESS;
}

Remove algorithm does not actually remove characters. Instead, it just perform a series of compactions.

For example,

remove(s.begin (), s.end (), ‘ ‘);
cout << "[" << s << "]" << endl; prints "[abcdefef]". Note the last two characters 'ef.' To print s without them, you must use the iterator which the remove function returns.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *