字符串替换函数 基于std::string

来源:互联网 发布:太原网络公司白猫网络 编辑:程序博客网 时间:2024/06/07 07:52

// 字符串替换
bool CCommonFunction::string_replace(const std::string str_new_str, const std::string str_old_str, std::string& str_str)
{
 try
 {
  size_t pos = 0;
  string::size_type new_str_length = str_new_str.length();
  string::size_type old_str_length = str_old_str.length();

  pos = str_str.find(str_old_str, pos);
  while (string::npos != pos)
  {
   str_str.replace(pos, old_str_length, str_new_str);
   pos = str_str.find(str_old_str, pos + new_str_length);
  }
 }
 catch(...)
 {
  return false;
 }

 return true;
}

 

 string str = "af.va.wef.aw.ecfcas##";

 string_replace("$", ".", str);  // 用$替换.