boost::erase_all 从字符串中删除多个字符

boost::erase_all to erase multiple chars from a string

本文关键字:删除 字符 erase all boost 字符串      更新时间:2023-10-16

如果我想使用 boost::erase_all 从字符串中删除所有 ,我可以这样做:

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

现在,我的字符串是"abc"。但是,如果我想从字符串中删除所有数字 (0 - 9),使用 boost::erase_all ,我必须为要删除的每个数字调用它一次。

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

我以为我可以使用 boost::is_any_of 一次将它们全部删除,因为这适用于其他 boost 字符串算法,例如 boost::split ,但is_any_of似乎不适用于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>&)’

也许我在这里忽略了一些明显的东西,或者 boost 中还有另一个功能可以做到这一点。我可以使用标准C++手动完成此操作,但只是好奇其他人如何使用 boost 来执行此操作。

感谢您的任何建议。

现在还提供:

boost::remove_erase_if(str, boost::is_any_of("123"));

boost 有一个 remove_if 版本,不需要你传入 begin 和 end 迭代器,但你仍然需要使用 end 迭代器对字符串调用 erase。

#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