A friend who has used Python should know that there is a replace function in Python's string, and its function is to replace the string,All are replaced by default. If a parameter is added, it will be replaced based on the set number.For example:
>>> Import string
>>> Str1 = "ab1ab2ab3ab4"
>>> Print string. Replace (str1, "AB", "cd ")
Cd1cd2cd3cd4
>>> Print string. Replace (str1, "AB", "cd", 1)
Cd1ab2ab3ab4
>>> Print string. Replace (str1, "AB", "cd", 2)
Cd1cd2ab3ab4
>>>
InC ++......You have not found a ready-made one.
The FunctionCodeTo facilitate future use:
String M_replace ( String STR, String Pattern, String Dstpattern, Int Count =-1 ){ String Retstr = "" ; String : Size_type Pos; Int I = 0 , L_count = 0 , Szstr = Str. Length (); If (- 1 = Count) // Replace all Count = Szstr; For (I = 0 ; I <szstr; I ++ ){ If ( String : NPOs = (Pos = Str. Find (pattern, I ))) Break ; If (Pos < Szstr) {retstr + = Str. substr (I, pos-I) + Dstpattern; I = POS + pattern. Length ()- 1 ; If (++ L_count> = Count) {I ++ ; Break ; }}} Retstr + = Str. substr (I ); Return Retstr ;}
Supplement:
At that time, I thought that the STL replace function could not be replaced with different lengths (it turns out to be wrong now), so it would be useless ......
Here we can use the replace function of STL to implement it:
View code
# Include <String > # Include <Iostream> Using Namespace STD; String M_replace ( String Strsrc, Const String & Oldstr, Const String & Newstr, Int Count =- 1 ){ String Strret = Strsrc; size_t POS = 0 ; Int Rochelle COUNT = 0 ; If (- 1 = Count) // Replace all Count = Strret. Size (); While (Pos = strret. Find (oldstr, POS ))! =String : NPOs) {strret. Replace (Pos, oldstr. Size (), newstr ); If (++ L_count> = count) Break ; POS + = Newstr. Size ();} Return Strret ;} Int Main (){ String Str1 = " Ab1ab2ab3 " ; String Str2 = " AB " ; String Str3 = " CD " ; String Str4 = " Cdefgh " ; Cout <M_replace (str1, str2, str3) <Endl; cout <M_replace (str1, str2, str3, 1 ) < Endl; cout <M_replace (str1, str2, str4) < Endl; cout <M_replace (str1, str2, str4, 2 ) < Endl ;}