字符串替换(replace)
将⽂本⽂件中指定的字符串替换成新字符串。由于⽬前的OJ系统暂时不能⽀持⽤户读⼊⽂件,我们编写程序从键盘输⼊⽂件中的内容,当输⼊的⼀⾏为end时,表⽰结束。end后⾯有两个字符串,要求⽤第⼆个字符串替换⽂本中所有的第⼀个字符串。
输⼊格式:
字符串replace函数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最常⽤的形式是place(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+='\n';
a+=m;
}
a+='\n';
getline(cin,b);
getline(cin,c);
int found;
found=a.find(b);
while(found!=-1)
{
b.size(),c);
found=a.find(b,found+1);
}cout<<a;
return0;
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论