1

我正在编写一个函数,它接受三个参数:

  • target: 目标字符串
  • oldVal: 旧子串
  • newVal: 新子字符串(替换 oldVal)

该函数的任务是查找字符串中所有出现的oldValtarget并将它们替换为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!"

但是,当我运行代码时,什么也没有发生。好像我陷入了无限循环。光标在终端上一直闪烁。我的功能有问题。我认为可能令人不安的是街区replace里的电话。这是在函数调用if中使用迭代器范围的正确方法吗?replace我可以用eraseand做到这一点insert。但我想在replace这里使用。

4

1 回答 1

3

字符串比你想象的要聪明得多。他们知道如何搜索,因此您不必自己动手。

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);

抱歉,这是草图;未经测试,但你明白了。

于 2013-07-11T18:21:28.247 回答