【南理oj】113 - 字符串替换(STL - string)

来源:互联网 发布:windows一直在检查更新 编辑:程序博客网 时间:2024/06/07 05:28

点击打开题目

字符串替换

时间限制:3000 ms  |  内存限制:65535 KB
难度:2
描述
编写一个程序实现将字符串中的所有"you"替换成"we"
输入
输入包含多行数据 

每行数据是一个字符串,长度不超过1000 
数据以EOF结束
输出
对于输入的每一行,输出替换后的字符串
样例输入
you are what you do
样例输出
we are what we do
来源
水题比赛
上传者
hzyqazasdf



这道题有两种思路:

①从原字符串找 " you " ,在原位置上替换为 " we "。最后输出。

②不断把原字符串赋值给 ans 字符串,若遇到 " you " 则赋值 " we "。最后输出ans字符串。


代码如下:

#include <cstdio>#include <string>#include <cstring>#include <iostream>#include <algorithm>using namespace std;int main(){string a;int loc;//"you"的位置 while (getline(cin,a)){loc = a.find("you",0);while (loc != string::npos)//查找失败返回string::npos的值 {a.replace(loc,3,"we");loc = a.find("you",0);}cout << a << endl;a.clear();}return 0;}


#include <cstdio>#include <string>#include <iostream> #include <algorithm>using namespace std;int main(){string a;while (getline(cin,a)){int l = a.size();string ans = "";for (int i = 0 ; i < l ;){if (i + 3 < l && a.substr(i,3) == "you"){ans += "we";i += 3;}else{ans += a[i];i++;}}a.clear();cout << ans << endl;}return 0;}


0 0