C++字符串替换

来源:互联网 发布:java后台管理框架源码 编辑:程序博客网 时间:2024/05/12 07:42


//该函数用于字符串的替换;
//参数1:是源字符串;
//参数2是要替换的字符子串;
//参数3是要替换成的字符子串

//例如下面例子:
// std::string str = "you are best";
// std::string str0 = "you";
// std::string str1 = "we";
//通过该函数得到的是 "we are best";

 void replace(std::string str, const std::string str0, const std::string str1)
 {
  std::string::size_type pos = 0;
  std::string::size_type len0 = str0.size();
  std::string::size_type len1= str1.size();

  while((pos = str.find(str0, pos)) != std::string::npos)
  {
   str.replace(pos, len0, str1);
   pos += len1;
  }
 }

0 0
原创粉丝点击