输入格式:
Xi’an Institute of Posts and Telecommunications is co-designed and implemented by the People’s Government of Shaanxi Province and the Ministry of Industry and Information Technology. The Institute is located in Xi’an, a historic city in Northwest China, famous for its magnificent ancient culture.
end (表示结束)
Institute (第一个字符串,要求用第二个字符串替换)
University (第二个字符串)
输出格式:
Xi’an University of Posts and Telecommunications is co-designed and implemented by the People’s Government of Shaanxi Province and the Ministry of Industry and Information Technology.The University is located in Xi’an, a historic city in Northwest China, famous for its magnificent ancient culture.
输入样例:
Xi’an Institute of Posts and Telecommunications is co-designed and implemented by the People’s Government of Shaanxi Province and the Ministry of Industry and Information Technology.
The Institute is located in Xi’an, a historic city in Northwest China, famous for its magnificent ancient culture.
end
Institute
University
输出样例:
Xi’an University of Posts and Telecommunications is co-designed and implemented by the People’s Government of Shaanxi Province and the Ministry of Industry and Information Technology.The University is located in Xi’an, a historic city in Northwest China, famous for its magnificent ancient culture.
解题:利用find函数和replace函数
find函数
1.string中find()返回值是字母在母串中的位置(下标记录),如果没有找到,那么会返回-1
2.查找某一给定位置后的子串的位置。例如str.find("bad",5),从母串下标为5开始搜索bad的位置,如果存在返回bad在母串的下标否则返回-1
3.查找所有子串在母串中出现的位置(此题就是如此)
模板:
int found=str.find("bad",0);
while(found!=-1)
{
cout<<found<<endl;//输出bad在母串的位置
found=str.find("bad",found+1);
}
4.反向查找子串在母串中出现的位置,通常我们可以这样来使用,当正向查找与反向查找得到的位置不相同说明子串不唯一。
str.rfind("bad");
replace函数
replace最常用的形式是str.replace(found,length,c)//在字符串str中从found位置开始用字符串c替换总长为length的字符串
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
string a,b,c,m;
getline(cin,a);
while(1)
{
getline(cin,m);
if(m=="end"){
break;
}
a+='
';
a+=m;
}
a+='
';
getline(cin,b);
getline(cin,c);
int found;
found=a.find(b);
while(found!=-1)
{
a.replace(found,b.size(),c);
found=a.find(b,found+1);
}cout<<a;
return 0;
}