六章练习:查找一段字段中的单词(不分大小写),并替换。

下面查找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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值