为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C++
守候你守候我 2019-12-12 14:09:58
有没有办法用另一个字符串替换所有出现的子字符串std::string?例如:void SomeFunction(std::string& str){   str = str.replace("hello", "world"); //< I'm looking for something nice like this}
查看完整描述

3 回答

?
噜噜哒

TA贡献1784条经验 获得超7个赞

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


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

  }

}



查看完整回答
反对 回复 2019-12-13
?
波斯汪

TA贡献1811条经验 获得超4个赞

#include <boost/algorithm/string.hpp> // include Boost, a C++ library

...

std::string target("Would you like a foo of chocolate. Two foos of chocolate?");

boost::replace_all(target, "foo", "bar");

这是关于replace_all 的官方文档。


查看完整回答
反对 回复 2019-12-13
  • 3 回答
  • 0 关注
  • 311 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信