c++/c字符串操作汇集
1. 字符串替换
void string_replace(std::string &strBig, const std::string &strsrc, const std::string &strdst) { std::string::size_type pos=0; std::string::size_type srclen=strsrc.size(); std::string::size_type dstlen=strdst.size(); while( (pos=strBig.find(strsrc, pos)) != std::string::npos) { strBig.replace(pos, srclen, strdst); pos += dstlen; } }
2.字符剔除(删除字符串中相同的单个字符)
void char_replace(char *s, char c) { char *m=s; char *n=s; while(*m) { if(*m!=c) *n++=*m; m++; } *n='\0'; }
3. 字符串分割
void strSplit(const string& strSrc, const string& sep, vector<string>& vectStr) { vectStr.clear(); std::string s; for (std::string::const_iterator Ite = strSrc.begin(); Ite != strSrc.end(); ++Ite) { if (sep.find(*Ite) != std::string::npos) { if (s.length()) vectStr.push_back(s); s = ""; } else { s += *Ite; } } if (s.length()) vectStr.push_back(s); }