字符串替换

无人久伴 提交于 2020-03-02 05:02:09

将文本文件中指定的字符串替换成新字符串。 由于目前的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.
作者: 张德慧
单位: 浙江大学
时间限制: 400 ms
内存限制: 64 MB
代码长度限
 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 } 

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!