下面查找our单词,并替换成对应的***,只能整个单词进行替换。your这个词不能替换,因为它是单词的一部分。
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main(int argc, char *argv[])
{
string a="Our home is your like ours,our OK";
string b="our",sep=" ,",c=a;
for(int i=0;i<c.length();i++) c[i]=tolower(c[i]);
size_t start=0,end=0;
while(start!=string::npos)
{
end=c.find_first_of(sep,start);
if(end==string::npos) break;
if(c.substr(start,end-start)==b)
{
a.replace(start,3,3,'*');
}
start=c.find_first_not_of(sep,end);
}
cout<<a<<endl;
return 0;
}
如果替换our的词是look,或更短的as,替换后会引起原串中索引变化,要进行处理。
长的情况,不调整索引,不会引起问题:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main(int argc, char *argv[])
{
string a="Our home is your like ours,our OK";
string b="our",sep=" ,",c=a;
for(int i=0;i<c.length();i++) c[i]=tolower(c[i]);
size_t start=0,end=0;
while(start!=string::npos)
{
end=c.find_first_of(sep,start);
if(end==string::npos) break;
if(c.substr(start,end-start)==b)
{
a.replace(start,3,"look");
c.replace(start,3,"look");//同时变化,保持a、c中的索引一致
}
start=c.find_first_not_of(sep,end);
}
cout<<a<<endl;
return 0;
}
如果替换成短的as,就要调整。
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main(int argc, char *argv[])
{
string a="Our home is your like ours,our OK";
string b="our",sep=" ,",c=a;
for(int i=0;i<c.length();i++) c[i]=tolower(c[i]);
size_t start=0,end=0;
while(start!=string::npos)
{
end=c.find_first_of(sep,start);
if(end==string::npos) break;
if(c.substr(start,end-start)==b)
{
a.replace(start,3,"as");
c.replace(start,3,"as");//同时变化,保持a、c中的索引一致
end--; //our比as多一个,所以结束索引对应起少一
}
start=c.find_first_not_of(sep,end);
}
cout<<a<<endl;
return 0;
}