c++ – Strip whitespace from a string

Question:

I want to remove all whitespace from a string , but I don't know how to do it. I've tried using replace but it didn't work.

Answer:

It has a ready-made algorithm in the library that makes the work a lot easier:

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main() {
    string str = " texto com espaços em branco ";
    str.erase(remove(str.begin(), str.end(), ' '), str.end());
    cout << str;
}

See working on ideone . And on repl.it. Also posted on GitHub for future reference .

Scroll to Top