1. 程式人生 > >string替換所有指定字符串(C++)

string替換所有指定字符串(C++)

con pos c++ clas 兩種 esp wan replace fin

C++的string提供了replace方法來實現字符串的替換,但是對於將字符串中某個字符串全部替換這個功能,string並沒有實現,我們今天來做的就是這件事。
首先明白一個概念,即string替換所有字符串,將"12212"這個字符串的所有"12"都替換成"21",結果是什麽?
可以是22211,也可以是21221,有時候應用的場景不同,就會希望得到不同的結果,所以這兩種答案都做了實現,代碼如下:

 1 #include   <string>     
 2 #include   <iostream>     
 3 using   namespace   std;     
4 string& replace_all(string& str, const string& old_value, const string& new_value) 5 { 6 while(true) 7 { 8 string::size_type pos(0); 9 if( (pos=str.find(old_value)) != string::npos ) 10 { 11 str.replace(pos,old_value.length(),new_value);
12 } 13 else { break; } 14 } 15 return str; 16 } 17 18 string& replace_all_distinct(string& str, const string& old_value, const string& new_value) 19 { 20 for(string::size_type pos(0); pos!=string::npos; pos+=new_value.length())
21 { 22 if( (pos=str.find(old_value,pos)) != string::npos ) 23 { 24 str.replace(pos,old_value.length(),new_value); 25 } 26 else { break; } 27 } 28 return str; 29 } 30 31 int main() 32 { 33 cout << replace_all(string("12212"),"12","21") << endl; 34 cout << replace_all_distinct(string("12212"),"12","21") << endl; 35 } 36 /* 37 輸出如下: 38 22211 39 21221 40 */

轉自:https://blog.csdn.net/chinawangfei/article/details/43116451

string替換所有指定字符串(C++)