南阳理工acm 题目113 字符串替换

1、题目信息

字符串替换

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

输入
输入包含多行数据
每行数据是一个字符串,长度不超过1000
数据以EOF结束


输出
对于输入的每一行,输出替换后的字符串

样例输入

you are what you do

样例输出
we are what we do

2、思路

1)整行接受字符串,遍历字符串,当元素为‘y'时,判断连同后两个元素是否等于‘you’如果等于,替换成‘we’同时字符串长度减一

2)题目中使用STL中的string头文件,其中的length、substr()、replace()函数更方便

3、代码

#include <cstdio>
#include <iostream>
#include <string>
using namespace std;
int main(){
    string s;
    int len;
    while(getline(cin,s)){ //整行接受字符串
        len=s.length();
        for(int i=0;i<len;i++){
            if(s[i]=='y'){
                if(s.substr(i,3)=="you"){
                    s.replace(i,3,"we");  //替换you为we
                    i=i+1;                //i需要指向we的e元素
                    len=len-1;            //字符长度减少1
                }
            }
        }
        cout<<s<<endl;
    }
    return 0;
}

4、扩展

对于整行接收字符串方法:

1)scanf()结合getchar()

char str[MaxSize];
scanf("%[^\n]",&str);
getchar();

%[ ],这个参数的意义是读入一个字符集合。[ ]是个集合的标志,因此%[ ]特指读入此集合所限定的那些字符,比如%[A-Z]是输入大写字母,一旦遇到不在此集合的字符便停止。如果集合的第一个字符是"^",这说明读取不在"^"后面集合的字符,既遇到"^"后面集合的字符便停止。注意此时读入的字符串是可以含有空格的,而且会把开头的空格也读进来

getchar()读取结尾的换行符

2)getline()接受string 对象

string str;
getline(cin,str);//读入string
注意要包含头文件#include <iostream>、#include <string>

猜你喜欢

转载自blog.csdn.net/sicauliuy/article/details/80114061