gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:21:35 25 4
gpt4 key购买 nike

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com