字符串替换
时间限制:3000 ms | 内存限制:65535 KB
难度:2
- 描述
- 编写一个程序实现将字符串中的所有"you"替换成"we"
- 输入
- 输入包含多行数据
每行数据是一个字符串,长度不超过1000
数据以EOF结束 输出 - 对于输入的每一行,输出替换后的字符串 样例输入
you are what you do
样例输出we are what we do
AC代码:
/*//从字符串s 下标5开始,查找字符串b ,返回b 在s 中的下标
position=s.find("b",5);
cout<<"s.find(b,5) is : "<<position<<endl;
*/
#include <string>
#include <iostream>
#include <iostream>
using namespace std;
int main()
{
string s;
int i,pos;
while(getline(cin,s))
{
pos=s.find("you",0);
//string::npos作为string的成员函数的一个长度参数时,表示“直到字符串结束(until the end of the string)”npos 恒为0xffffffff
while(pos!=string::npos)//在字符串结束前找到了匹配项,即找到了"you"的位置(字符串中还有"you",继续替换),直至所有的"you"被替换
{
s.replace(pos,3,"we");//将从pos处开始的三位字符换成"we"
pos=s.find("you",pos+1);//替换后,从下一位开始继续找
}
cout<<s<<endl;
}
return 0;
}