【问题标题】:Replacing all occurrences of a substring with another substring in a long string用长字符串中的另一个子字符串替换所有出现的子字符串
【发布时间】:2013-07-10 03:22:35
【问题描述】:

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

  • 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!"

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

【问题讨论】:

  • 当您进行就地更换时,需要进行一些棘手的簿记来跟踪您的位置。如果替换文本比被替换的文本短,你可以很容易地做到这一点,但如果替换文本比被替换的文本长,你必须将字符串的尾部移出足够远以便为新文本留出空间;如果你反复这样做,你最终会做很多复制,这会很慢。
  • Pete Becker 解决方案的一个版本可以在我的帖子中找到:-> stackoverflow.com/questions/20406744

标签: c++ string c++11 iterator replace


【解决方案1】:

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

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 - 谢谢。我在 first 的地方修复了它。 :-(
  • 我认为这一行“pos = match_pos + target.size();”应该是“pos = match_pos + newVal.size();”
猜你喜欢
  • 2011-04-06
  • 2013-12-29
  • 2011-06-06
  • 1970-01-01
  • 1970-01-01
  • 2011-12-19
  • 1970-01-01
  • 1970-01-01
  • 2014-12-23
相关资源
最近更新 更多