将文本文件中指定的字符串替换成新字符串。 由于目前的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.
输入样例:
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.
1 #include <bits/stdc++.h>
2 using namespace std;
3
4 int main()
5 {
6 string str,s1,s2,s;
7 int i,flag;
8 getline(cin,str);
9 while(1)
10 {
11 getline(cin,s);
12 i=s.compare("end");
13 if(i==0)
14 break;
15 str+='\n';
16 str+=s;
17 }
18 str+='\n';
19 cin>>s1;
20 cin>>s2;
21 flag=str.find(s1);
22 while(flag!=string::npos)
23 {
24 str.replace(flag,s1.length(),s2);
25 flag=str.find(s1,flag+1);
26 }
27 cout<<str;
28 return 0;
29 }
来源:https://www.cnblogs.com/esther6/p/10431891.html