c++ 實現字串中替換字串,也可去掉字串中特定字串
阿新 • • 發佈:2019-01-27
int string_replase(string &s1, const string &s2, const string &s3) { string::size_type pos = 0; string::size_type a = s2.size(); string::size_type b = s3.size(); while ((pos = s1.find(s2,pos)) != string::npos) { s1.replace(pos, a, s3); pos += b; } return 0; } string s2 = "###ip##"; string s1 = "http://123###ip##678.com"; string s3 = "192"; string_replase(s1, s2, s3);
//第二種替換字串的方法用erase()和insert() void string_replace_2(string&s1,const string&s2,const string&s3) { string::size_type pos=0; string::size_type a=s2.size(); string::size_type b=s3.size(); while((pos=s1.find(s2,pos))!=string::npos) { s1.erase(pos,a); s1.insert(pos,s3); pos+=b; } }