7-43 字符串替换 (10 分)
将文本文件中指定的字符串替换成新字符串。 由于目前的OJ系统暂时不能支持用户读入文件,我们编写程序从键盘输入文件中的内容,当输入的一行为end时,表示结束。end后面有两个字符串,要求用第二个字符串替换文本中所有的第一个字符串。
输入格式:
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.
首先是string函数当中的find函数,和replace函数
find函数是在字符串找到子字符串的位置,如果找到了返回子字符串首字母的位置,否则返回-1;
replace函数第一个参数是位置,第二个参数是被替换字符串的长度,第三个参数是字符串。
#include <bits/stdc++.h>
using namespace std;
const int maxs = 1e4;
int main(){
string str[maxs],a,b;
int now=0;
while(getline(cin,str[++now])&&str[now]!="end");//每次输入文本的一行,直到回车终止
//注意这里用++now,而不用now++,因为now++之后,str[now]永远是下一个位置,所以一直不能终止
getline(cin,a);
getline(cin,b);
int pos;//position
for(int i=0;i<now;i++){
while((pos=str[i].find(a))!=-1){
//printf("%d\n",pos);//看看被替换词在本句中的位置,返回首个字母的位置
str[i].replace(pos,a.size(),b);//把a.size()大小的位置用b来替换
}
}
for(int i=0;i<now;i++){
cout << str[i] << endl;
}
return 0;
}