C++ 用长字符串中的另一个子字符串替换所有出现的子字符串
我正在编写一个函数,它包含三个参数:C++ 用长字符串中的另一个子字符串替换所有出现的子字符串,c++,string,c++11,iterator,replace,C++,String,C++11,Iterator,Replace,我正在编写一个函数,它包含三个参数: 目标:目标字符串 oldVal:旧的子字符串 newVal:新的子字符串(替换旧的val) 此函数的任务是在target字符串中查找所有出现的oldVal,并将其替换为newVal 这就是我目前拥有的功能: std::string replace_old_with_new(std::string target, std::string oldVal, std::string newVal) { std::cout << "targe
:目标字符串目标
:旧的子字符串oldVal
:新的子字符串(替换旧的val)newVal
target
字符串中查找所有出现的oldVal
,并将其替换为newVal
这就是我目前拥有的功能:
std::string replace_old_with_new(std::string target, std::string oldVal, std::string newVal) {
std::cout << "target : " << target << ", oldVal: " << oldVal << ", newVal: " << newVal << "\n";
std::string::iterator begin = target.begin();
std::string::iterator oldValBegin = oldVal.begin();
while (begin != target.end()) {
if (*begin == *oldValBegin) {
target = target.replace(begin, begin + oldVal.size(), oldVal);
begin = target.begin();
} else {
++begin;
}
}
return target;
}
应返回字符串-
"Hello! bye bye!"
但是,当我运行代码时,什么都没有发生。我似乎陷入了一个无限循环。终端上的光标一直闪烁。我的功能有问题。我认为最麻烦的是
if
块中的replace
调用。这是在replace
函数调用中使用迭代器范围的正确方法吗?我可以用擦除
和插入
来执行此操作。但是我想在这里使用replace
。字符串比您认为的要聪明得多。他们知道如何搜索,所以你不必自己搜索
int pos = 0;
int match_pos;
std::string result;
while ((match_pos = target.find(oldVal, pos)) != std::string::npos) {
result += target.substr(pos, match_pos - pos);
result += newVal;
pos = match_pos + target.size();
}
result += target.substr(pos, std::string::npos);
对不起,这是一张素描;未经测试,但您已了解情况。可能重复进行现场更换时,需要一些复杂的簿记来跟踪您的位置。如果替换文本比被替换的文本短,您可以相当容易地完成,但是如果替换文本比被替换的文本长,您必须将字符串的尾部向外移动足够远,以便为新文本留出空间;如果你反复这样做,你最终会做大量的复制,这使得复制速度非常慢。皮特·贝克尔的解决方案的一个版本可以在我的帖子中找到:->谢谢@Pete。直到
find
功能仍然没有到达。所以,我不知道。我会试试你的解决方案。@Nawaz-谢谢。我一开始就把它修好了-(我认为这行“pos=match_pos+target.size();”应该是“pos=match_pos+newVal.size();”
int pos = 0;
int match_pos;
std::string result;
while ((match_pos = target.find(oldVal, pos)) != std::string::npos) {
result += target.substr(pos, match_pos - pos);
result += newVal;
pos = match_pos + target.size();
}
result += target.substr(pos, std::string::npos);