【问题标题】:boost::erase_all to erase multiple chars from a stringboost::erase_all 从字符串中擦除多个字符
【发布时间】:2012-05-09 20:10:08
【问题描述】:

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

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

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

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

我想我可以使用 boost::is_any_of 一次性删除它们,因为它适用于其他提升字符串算法,例如 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::erase_all 的优势在于它能够识别和擦除字符序列。但是,您只是想删除单个字符,std::remove_if 非常适合。

标签: c++ string boost


【解决方案1】:

现在还有:

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

【讨论】:

    【解决方案2】:

    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

    【讨论】:

    • hm,但是如果不是数字而是特殊字符(例如"-&gt;&lt;&amp;%),你会怎么做?
    • @CarstenGreiner:您可以使用boost::is_any_of("-&gt;&lt;&amp;%") 代替::isdigit
    猜你喜欢
    • 2019-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-30
    • 1970-01-01
    • 1970-01-01
    • 2013-08-20
    • 2023-01-11
    相关资源
    最近更新 更多