replace_all这样常用的操作在C++却没直接提供,只好自己写个备忘。
// 按anqiang12的提醒改进:
// 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);
}
本文介绍了如何在C++中实现类似std::replace_all的字符串替换功能,以及如何使用trim方法去除字符串首尾指定字符。通过实例代码详细解释了操作流程和应用场景。
6181

被折叠的 条评论
为什么被折叠?



