我正在写一个函数,它接受三个参数:
target
: 目标字符串oldVal
: 旧子串newVal
: 新的子字符串(替换旧的Val)
该函数的任务是找出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;
}
下面调用上面的函数:
replace_old_with_new("Hello! hi hi!", "hi", "bye");
应该返回字符串 -
"Hello! bye bye!"
但是,当我运行代码时,没有任何反应。好像我陷入了无限循环。光标在终端上不断闪烁。我的功能有问题吗?我认为可能麻烦的是 if
block 中的 replace
调用。这是在 replace
函数调用中使用迭代器范围的正确方法吗?我可以使用 erase
和 insert
来做到这一点。但是我想在这里使用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);
对不起,这是草图;未经测试,但您明白了。
关于c++ - 用长字符串中的另一个子字符串替换所有出现的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17600421/