#include<iostream>
#include<string>
#include<vector>
using namespace std;
/*
void func(string &s, string &oldVal,const string &newVal)
{
string::size_type size = oldVal.size();
for (string::size_type i = 0;i<s.length()-size; i++)
{
if (s.substr(i,size)==oldVal)
{
s.replace(i, size, newVal);
}
}
}*/
void func1(string &s, string &oldValue, string &newValue)
{
int _size = oldValue.size();
string::iterator it1 = s.begin();
string::iterator it2 = newValue.begin();
string::iterator it3 = newValue.begin();
for (it1; it1 <= (s.end() - oldValue.size() + 1); ++it1)
{
it1 = s.erase(it1, it1 + _size);//返回的是最后一个被会删除的元素之后的位置
s.insert(it1, it2, it3);//原因在于insert()函数返回
}
}
void func(string &s, string &oldValue, string &newValue)
{
int _size = oldValue.size();
string::iterator it1 = s.begin();
string::iterator it2 = newValue.begin();
string::iterator it3 = newValue.end();
for (; it1 <= (s.end() - _size + 1); ++it1)
{
if ((s.substr(it1 - s.begin(), _size) == oldValue))
{
it1 = s.erase(it1, it1 + _size);
it1 = s.insert(it1, it2, it3);
//advance(it1, _size);
it1 += _size;
}
}
}
int main(int argc, char**argv)
{
string s = "2134bbaaaaabbaaa";
string oldval = "bb";
string newval = "kkk";
func(s, oldval, newval);
cout << s << endl;
system("pause");
return 0;
}
给你三个string str oldstr newstr 用newstr替换str里的oldstr
最新推荐文章于 2023-01-07 16:23:34 发布