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

Remove specific consecutive characters duplications from std::string

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

例如,当我有通配符模式并且我只想删除连续的星号时 (*)
/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

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