题解 | #单词替换#

单词替换

https://www.nowcoder.com/practice/5b58a04679d5419caf62c2b238e5c9c7

# include<stdio.h>
#include<iostream>
using namespace std;
int main(){
	string s,tag,sub;
while(getline(cin,s)){
	cin>>sub;
	cin>>tag;
	int index = 0;
	int count = 0;
	while((index=s.find(sub,index))<s.length())//迭代
	{	
	  if((s[index-1]==' '&&s[index+sub.length()]==' ')||(index==0&&s[index+sub.length()]==' ')||(s[index-1]==' '&&index==s.length()-1))//1.单词在中间的情况  2.单词在最开头的情况 3.单词在最末尾的情况
			s.replace(index,sub.length(),tag);//替换 (index ,length ,"tag")
		index++;
	}
	cout<<s;
	
	
}
	
} 

全部评论

相关推荐

2025-12-22 16:31
已编辑
桂林电子科技大学 Python
很奥的前端仔:如果你接了offer 临时又说不去 hr确实要多做一些工作。 当然如果是接offer之前当我没说
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务