如何在标准字符串中搜索/查找和替换? [英] How do I Search/Find and Replace in a standard string?

查看:104
本文介绍了如何在标准字符串中搜索/查找和替换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法用 std :: string



中的另一个字符串替换子字符串的所有出现>例如:

  void SomeFunction(std :: string& str)
{
str = str .replace(hello,world); //<我正在寻找像这样的东西
}


解决方案

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

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


Is there a way to replace all occurrences of a substring with another string in std::string?

For instance:

void SomeFunction(std::string& str)
{
   str = str.replace("hello", "world"); //< I'm looking for something nice like this
}

解决方案

Why not implement your own replace?

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

这篇关于如何在标准字符串中搜索/查找和替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆