如何查找和替换字符串?

新手上路,请多包涵

如果 sstd::string ,那么是否有类似以下的功能?

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

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

阅读 432
2 个回答

替换第一个匹配项

使用 std::string::findstd::string::replace 的组合。

找到第一个匹配项:

 std::string s;
std::string toReplace("text to replace");
size_t pos = s.find(toReplace);

替换第一个匹配项:

 s.replace(pos, toReplace.length(), "new text");


为您提供方便的简单功能:

 void replace_first(
    std::string& s,
    std::string const& toReplace,
    std::string const& replaceWith
) {
    std::size_t pos = s.find(toReplace);
    if (pos == std::string::npos) return;
    s.replace(pos, toReplace.length(), replaceWith);
}

用法:

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

演示。


替换所有匹配项

使用 std::string 作为缓冲区定义此 O(n) 方法:

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

演示。


促进

或者,使用 boost::algorithm::replace_all

 #include <boost/algorithm/string.hpp>
using boost::replace_all;

用法:

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

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

有没有像下面这样的功能?

另一种( _除了使用 boost 和不同答案中给出的其他方法_)可能的方法是使用 std::regex_replace 如下所示:

     std::string s{"my name is my name and not my name mysometext myto"}; //this is the original line

    std::string replaceThis = "my";
    std::string replaceWith = "your";

    std::regex pattern("\\b" + replaceThis + "\\b");

    std::string replacedLine = std::regex_replace(s, pattern, replaceWith);

    std::cout<<replacedLine<<std::endl;

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

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