removing whitspaces with STL algorithms
Hello friends,
I'm refreshing my knowleadge about stl containers and algorithms and
learning new things.
I came accross a simple but interesting problem. Say, I need to remove whitespace
characters from string. Here's my first attempt:
Code:
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
using namespace std;
int main ( )
{
string str = "ABC ND001";
remove_if ( str.begin ( ), str.end ( ), isspace );
cout << str << endl;
}
if you execute this code youll see that result is: ABCND0011 which is not what I want
because ND001 is simply shifted to the left and last 1 stayed in string.
Now my solution to this problem is this:
Code:
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
#include <cctype>
using namespace std;
int main ( )
{
string str = "ABC ND001";
string res;
remove_copy_if ( str.begin ( ), str.end ( ), back_inserter (res), isspace );
cout << res << endl;
}
Now this is what I want.
However, this solution requires iterator library (back_inserter), another string to
store result and copying elements, so it's more problematic regarding performance.
I wonder if there is more elegant way to do this...
If someone has any suggestion, I would appreciate it.
Thanks