64,849
社区成员
![](https://csdnimg.cn/release/cmsfe/public/img/topic.427195d5.png)
![](https://csdnimg.cn/release/cmsfe/public/img/me.40a70ab0.png)
![](https://csdnimg.cn/release/cmsfe/public/img/task.87b52881.png)
![](https://csdnimg.cn/release/cmsfe/public/img/share-circle.3e0b7822.png)
#include <string>
#include <iostream>
using namespace std;
string& replace_all(string& str,const string& old_value,const string& new_value)
{
while(true)
{
string::size_type pos(0);
if( (pos=str.find(old_value))!=string::npos )
str.replace(pos,old_value.length(),new_value);
else break;
}
return str;
}
string& replace_all_distinct(string& str,const string& old_value,const string& new_value)
{
for(string::size_type pos(0); pos!=string::npos; pos+=new_value.length()) {
if( (pos=str.find(old_value,pos))!=string::npos )
str.replace(pos,old_value.length(),new_value);
else break;
}
return str;
}
int main()
{
cout << replace_all(string("12212"),"12","21") << endl;
cout << replace_all_distinct(string("12212"),"12","21") << endl;
}
//output:
//22211
//21221
Examines each element in a range and replaces it if it matches a specified value.
template<class ForwardIterator, class Type>
void replace(
ForwardIterator _First,
ForwardIterator _Last,
const Type& _OldVal,
const Type& _NewVal
);
_First
A forward iterator pointing to the position of the first element in the range from which elements are being replaced.
_Last
A forward iterator pointing to the position one past the final element in the range from which elements are being replaced.
_OldVal
The old value of the elements being replaced.
_NewVal
The new value being assigned to the elements with the old value.