1. 程式人生 > >C++,替換字串的全部目標子串

C++,替換字串的全部目標子串

replace_all這樣常用的操作在C++卻沒直接提供,只好自己寫個備忘。

// replace all occurance of t in s to w
void replace_all(std::string & s, std::string const & t, std::string const & w)
{
  string::size_type pos = s.find(t), t_size = t.size(), r_size = w.size();
  while(pos != std::string::npos){ // found 
    s.replace(pos, t_size, w); 
	pos = s.find(t, pos + r_size ); 
  }
}

string trim(string const & s, char c = ' ')
{
  string::size_type a = s.find_first_not_of(c);
  string::size_type z = s.find_last_not_of(c);
  if(a == string::npos){
    a = 0;
  }

  if(z == string::npos){
    z = s.size();
  }
  return s.substr(a, z);
}