c++stringboost

boost::erase_all to erase multiple chars from a string


If I want to remove all ones from a string using boost::erase_all, I can do this:

boost::erase_all( "a1b1c1", "1" );

Now, my string is "abc". However, if I want to remove all digits (0 - 9) from a string, using boost::erase_all, I have to call it once for each digit I wish to remove.

boost::erase_all( "a1b2c3", "1" );
boost::erase_all( "a1b2c3", "2" );
boost::erase_all( "a1b2c3", "3" );

I thought I could use boost::is_any_of to remove them all at once as that works with other boost string algorithms such as boost::split, but is_any_of does not seem to work with erase_all:

boost::erase_all( "a1b2c3", boost::is_any_of( "123" ) );

// compile error
boost/algorithm/string/erase.hpp:593:13: error: no matching 
function for call to ‘first_finder(const   
boost::algorithm::detail::is_any_ofF<char>&)’

Perhaps I've over-looked something obvious here or there's another function within boost that's meant to do this. I can do it manually with standard C++, but just curious how others might be using boost to do this.

Thanks for any advice.


Solution

  • boost has a version of remove_if that doesn't require you to pass in begin and end iterators, but you will still need to call erase on the string with the end iterator.

    #include <boost/range/algorithm/remove_if.hpp>
    ...
    std::string str = "a1b2c3";
    str.erase(boost::remove_if(str, ::isdigit), str.end());
    

    http://www.boost.org/doc/libs/1_49_0/libs/range/doc/html/range/reference/algorithms/mutating/remove_if.html