【问题标题】:Remove specific consecutive characters duplications from std::string从 std::string 中删除特定的连续字符重复
【发布时间】:2019-08-26 18:53:18
【问题描述】:

也许任何人都有一种有效的方法来删除特定字符的连续重复,最好使用内置的字符串操作,而无需显式遍历字符串字符。

例如,当我有通配符模式并且我只想删除连续的星号 (*)
/aaaa/***/bbbb/ccc/aa/*****/dd --> /aaaa/*/bbbb/ccc/aa/*/dd

对于所有重复重复的字符,我可以通过以下方式使用std::unique

str.erase( std::unique(str.begin(), str.end()), str.end());

但是只有特定的字符呢。

【问题讨论】:

  • 您可以使用正则表达式替换,但在这种情况下,自制一些东西可能会更好
  • std::remove_if 与可变 lambda 一起使用,然后是 erase()。就这么简单。
  • @SamVarshavchik 是否保证元素被连续访问?
  • 根据cppreference是的。
  • @SamVarshavchik 你能链接这篇文章吗?我没找到。编辑:我猜算法接受前向迭代器,所以如果你通过其中一个,你就可以保证连续访问。令我困扰的是,我找不到明确的说法。如果您传递一个随机访问迭代器,我不明白为什么不允许它执行谓词的乱序评估。特别是因为该算法接受ExecutionPolicy,这意味着它似乎是多线程的。

标签: c++ string algorithm unique std


【解决方案1】:

您可以使用与 lambda 表达式相同的算法 std::unique

例如

#include <iostream>
#include <string>
#include <functional>
#include <iterator>
#include <algorithm>

int main()
{
    std::string s = "/aaaa/***/bbbb/ccc/aa/*****/dd"; 
    char c = '*';

    s.erase( std::unique( std::begin( s ), std::end( s ), 
                          [=]( const auto &c1, const auto &c2 ) { return c1 == c && c1 == c2; } ),
             std::end( s ) ); 

    std::cout << s << '\n';             
}

程序输出是

/aaaa/*/bbbb/ccc/aa/*/dd

或者您可以删除一组重复的字符。例如

#include <iostream>
#include <string>
#include <functional>
#include <iterator>
#include <algorithm>
#include <cstring>

int main()
{
    std::string s = "/aaaa/***/bbbb/ccc/aa/*****/dd"; 
    const char *targets = "*b";

    auto remove_chars = [=]( const auto &c1, const auto &c2 )
    {
        return strchr( targets, c1 ) && c1 == c2;
    };
    s.erase( std::unique( std::begin( s ), std::end( s ), remove_chars ), 
             std::end( s ) ); 

    std::cout << s << '\n';             
}

程序输出是

/aaaa/*/b/ccc/aa/*/dd

在最后一个示例中,我假设字符 '\0' 不包含在字符串中。否则,您必须在 lambda 中的逻辑表达式中再添加一个子表达式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-25
    • 1970-01-01
    • 1970-01-01
    • 2018-08-05
    • 1970-01-01
    • 2017-04-03
    • 2015-01-26
    • 1970-01-01
    相关资源
    最近更新 更多