gpt4 book ai didi

c++ - 使用 C++ 替换 std::string 中的子字符串但不是全部

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:26:06 27 4
gpt4 key购买 nike

我是 C++ 的新手,我知道我的帖子可能与其他帖子重复,但我想做的是替换字符串中的子字符串,但不是全部。

这是我的查找和替换子字符串函数,它的工作方式与其他替换函数一样:

void findAndReplaceAll(std::string& data, std::string toSearch, std::string replaceStr)
{
//Get the first occurrence
size_t pos = data.find(toSearch);

//Repeat till end is reached
while (pos != std::string::npos)
{
//Replace this occurrence of Sub String
data.replace(pos, toSearch.size(), replaceStr);
//Get the next occurrence from the current position
pos = data.find(toSearch, pos + replaceStr.size());
}
}

我的主要功能:

int main()
{
std::string format = "h 'o''cloch' a, zzzz";
findAndReplaceAll(format, "h", "%h");
return 0;
}

我想要的输出只是替换第一个“h”而不是第二个“h”。

"%h 'o''cloch' a,zzzz";

最佳答案

您可以向您的函数添加一个参数,告诉您需要多少个字符后才能停止替换子字符串。

函数原型(prototype)看起来像这样:void findAndReplaceAll(std::string& data, std::string toSearch, std::string replaceStr, int stopAfterXCharacters)

然后您需要将 while 循环更改为在读取了一定数量的字符后停止。

或者,您可以使用一个仅替换一定数量子字符串的函数,在您的情况下,如果一个子字符串已更改,您的函数将返回。

关于c++ - 使用 C++ 替换 std::string 中的子字符串但不是全部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58640681/

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