Remove any spaces within a string - C++ STL

C++ examples for STL:string

Description

Remove any spaces within a string

Demo Code

#include <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  www. ja  va  2 s . c  o 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;
}

Result


Related Tutorials