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

有没有办法用另一个字符串替换所有出现的子字符串std::string?


例如:


void SomeFunction(std::string& str)

{

   str = str.replace("hello", "world"); //< I'm looking for something nice like this

}


守候你守候我
浏览 324回答 3
3回答

噜噜哒

为什么不实施自己的替换?void myReplace(std::string& str,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;const std::string& oldStr,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;const std::string& newStr){&nbsp; std::string::size_type pos = 0u;&nbsp; while((pos = str.find(oldStr, pos)) != std::string::npos){&nbsp; &nbsp; &nbsp;str.replace(pos, oldStr.length(), newStr);&nbsp; &nbsp; &nbsp;pos += newStr.length();&nbsp; }}

波斯汪

#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 的官方文档。
打开App,查看更多内容
随时随地看视频慕课网APP