用另一个字符串替换一个字符串的一部分

新手上路,请多包涵

如何使用 标准 C++ 库 将字符串的一部分替换为另一个字符串?

 QString s("hello $name");  // Example using Qt.
s.replace("$name", "Somename");

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

阅读 1.5k
2 个回答

有一个函数可以在字符串中查找子字符串( find ),还有一个函数可以用另一个字符串( replace )替换字符串中的特定范围,因此您可以将它们组合到得到你想要的效果:

 bool replace(std::string& str, const std::string& from, const std::string& to) {
    size_t start_pos = str.find(from);
    if(start_pos == std::string::npos)
        return false;
    str.replace(start_pos, from.length(), to);
    return true;
}

std::string string("hello $name");
replace(string, "$name", "Somename");


在回应评论时,我认为 replaceAll 可能看起来像这样:

 void replaceAll(std::string& str, const std::string& from, const std::string& to) {
    if(from.empty())
        return;
    size_t start_pos = 0;
    while((start_pos = str.find(from, start_pos)) != std::string::npos) {
        str.replace(start_pos, from.length(), to);
        start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
    }
}

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

升压解决方案怎么样:

 boost::replace_all(value, "token1", "token2");

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

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