Monday, November 21, 2011

A trivial character search and replace method in C++

A very long time ago I was searching for ways to replace individual characters in a string and some of the methods was summarized in a small test program. I found that test program in an old folder on my computer which I almost forgot. So, I share that little code with the world. It follows.

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

using namespace std;

bool is_punct( const char& c )
{
 return ispunct( c );
}

bool is_l( const char& c )
{
 return 'l'==c;
}

struct mycomp
{
 bool operator()(const char& o)
 {
  return ispunct( o );
 }
};

int main()
{
 // Remove all characters that "ispunct" using a function.
 string s = "hello, world!";
 s.erase( remove_if( s.begin(), s.end(), &is_punct ), s.end() );
 cout << s << '\n';

 // Remove all characters that "ispunct" using a functor.
 s = "hello, world!";
 s.erase( remove_if( s.begin(), s.end(), mycomp() ), s.end() );
 cout << s << '\n';

 // Replace all 'l' with 'L' using a function.
 s = "hello, world!";
 replace_if( s.begin(), s.end(), &is_l, 'L' );
 cout << s << '\n';
}

0 kommentarer:

Post a Comment