c++ - 用长字符串中的另一个子字符串替换所有出现的子字符串

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

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

  • 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 函数调用中使用迭代器范围的正确方法吗?我可以使用 eraseinsert 来做到这一点。但是我想在这里使用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/

相关文章:

c++ - 处理派生类指针 vector 的正确方法?

c++ - std::find_if_not() 返回什么类型?

c++ - 如何在 Cmake 中定义传递 CXX_STANDARD C++11

c++ - C++如何获取字符串的最后一个字符?

c# - .NET 字符串和引用类型参数

c++ - 在编译时使用 CRC32 算法对字符串进行哈希处理

C++:使用模板时未覆盖函数

c++ - 一段时间内声明中的奇怪行为 C++

java - 使用指定分隔符拆分字符串,不遗漏空元素

java - String.format - 用点填充字符串