gpt4 book ai didi

c++ - 用给定的字符串替换字符串中的偶数位

转载 作者:行者123 更新时间:2023-12-05 03:19:46 27 4
gpt4 key购买 nike

我知道如何用字符串 ( How to replace all occurrences of a character in string? ) 中的另一个字符替换所有出现的字符

但是如果我想用给定的字符串替换字符串中的所有偶数怎么办?我对 replacereplace_ifbasic_string 的成员 replace/find 函数感到困惑类,因为函数签名要求 old_val 和 new_val 是同一类型。但是old_val是char,new_val是string。有什么有效的方法可以做到这一点,而不是使用多个循环?

例如如果输入字符串是

"asjkdn3vhsjdvcn2asjnbd2vd"

替换文本是

"whatever"

,结果应该是

"asjkdn3vhsjdvcnwhateverasjnbdwhatevervd"

最佳答案

您可以使用 std::string::replace() 将字符替换为字符串。一个工作示例如下:

#include <string>
#include <algorithm>
#include <iostream>
#include <string_view>

void replace_even_with_string(std::string &inout)
{
auto is_even = [](char ch)
{
return std::isdigit(static_cast<unsigned char>(ch)) && ((ch - '0') % 2) == 0;
};
std::string_view replacement_str = "whatever";
auto top = std::find_if(inout.begin(), inout.end(), is_even) - inout.begin();
for (std::string::size_type pos{};
(pos = (std::find_if(inout.begin() + pos, inout.end(), is_even) - inout.begin())) < inout.length();
pos += replacement_str.length() - 1)
{
inout.replace(pos, 1, replacement_str.data());
}
}

int main()
{
std::string test = "asjkdn3vhsjdvcn2asjnbd2vd";
std::cout << test << std::endl;
replace_even_with_string(test);
std::cout << test << std::endl;
}

关于c++ - 用给定的字符串替换字符串中的偶数位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73343501/

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