如何在标准字符串中搜索/查找和替换?

新手上路,请多包涵

对于 std::string s,如何用另一个字符串替换所有出现的子字符串?

 std::string s ("One hello, two hellos.");
s = s.replace("hello", "world");  // something like this

原文由 Adam Tegen 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 458
2 个回答

为什么不实施自己的替换?

 void myReplace(std::string& str,
               const std::string& oldStr,
               const std::string& newStr)
{
  std::string::size_type pos = 0u;
  while((pos = str.find(oldStr, pos)) != std::string::npos){
     str.replace(pos, oldStr.length(), newStr);
     pos += newStr.length();
  }
}

原文由 yves Baumes 发布,翻译遵循 CC BY-SA 3.0 许可协议

性能 O(n) 替换所有

许多其他答案重复调用 std::string::replace ,这需要重复覆盖字符串,导致性能不佳。相比之下,这使用 std::string 缓冲区,以便字符串的每个字符只遍历一次:

 void replace_all(
    std::string& s,
    std::string const& toReplace,
    std::string const& replaceWith
) {
    std::string buf;
    std::size_t pos = 0;
    std::size_t prevPos;

    // Reserves rough estimate of final size of string.
    buf.reserve(s.size());

    while (true) {
        prevPos = pos;
        pos = s.find(toReplace, pos);
        if (pos == std::string::npos)
            break;
        buf.append(s, prevPos, pos - prevPos);
        buf += replaceWith;
        pos += toReplace.size();
    }

    buf.append(s, prevPos, s.size() - prevPos);
    s.swap(buf);
}

用法:

 replace_all(s, "text to replace", "new text");


完整示例:
 #include <iostream>
#include <sstream>

void replace_all(
    std::string& s,
    std::string const& toReplace,
    std::string const& replaceWith
) {
    std::string buf;
    std::size_t pos = 0;
    std::size_t prevPos;

    // Reserves rough estimate of final size of string.
    buf.reserve(s.size());

    while (true) {
        prevPos = pos;
        pos = s.find(toReplace, pos);
        if (pos == std::string::npos)
            break;
        buf.append(s, prevPos, pos - prevPos);
        buf += replaceWith;
        pos += toReplace.size();
    }

    buf.append(s, prevPos, s.size() - prevPos);
    s.swap(buf);
}

int main() {
    std::string s("hello hello, mademoiselle!");
    replace_all(s, "hello", "bye");
    std::cout << s << std::endl;
}

输出:

 bye bye, mademoiselle!


注意: 此答案的先前版本使用 std::ostringstream ,这有一些开销。根据@LouisGo 的建议,最新版本使用 std::string::append 代替。

原文由 Mateen Ulhaq 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题