c++ - 从 std::string 中删除特定的连续字符重复

标签 c++ string algorithm unique std

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

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

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

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

但是只有特定的字符呢?

最佳答案

您可以对 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 中的逻辑表达式再添加一个子表达式。

关于c++ - 从 std::string 中删除特定的连续字符重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57663411/

相关文章:

c++ - 如何按字节数对 C(或 C++)对象进行类型转换

c++ - 在 C++ 中使用随机数生成一系列可重复的数字

c++ - 我在哪里可以找到 string.cpp 的来源

Java:替换字符串(用括号!)

c - 我应该使用 "rand % N"还是 "rand()/(RAND_MAX/N + 1)"?

c++ - 这个模数我做错了什么?

android - 我如何使用带微调器的开关?

java - 如何通过在android中前后添加双引号来传递文本

java - 迭代深化A*星解释

algorithm - 为什么提出启发式?