C++ string erase() Remove any spaces within a string

Description

C++ string erase() Remove any spaces within a string

#include <cstdlib>
#include <cstdio>
#include <iostream>
using namespace std;

string removeSpaces(const string& source)
{
    // make a copy of the source string so that we don't modify it
    string s = source;//from w  w w.j  ava 2  s .co  m

    size_t offset;
    while((offset = s.find(" ")) != string::npos){
        s.erase(offset, 1);
    }
    return s;
}

int main(int argc, char* pArgs[])
{
    string s2("This is a test string");
    cout << "<" << s2 << "> minus spaces = <" << removeSpaces(s2) << ">" << endl;

    return 0;
}



PreviousNext

Related