字符串替换 find函数和replace函数的应用

7-43 字符串替换 (10 分)
将文本文件中指定的字符串替换成新字符串。 由于目前的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.

首先是string函数当中的find函数,和replace函数
find函数是在字符串找到子字符串的位置,如果找到了返回子字符串首字母的位置,否则返回-1;
replace函数第一个参数是位置,第二个参数是被替换字符串的长度,第三个参数是字符串。

#include <bits/stdc++.h>

using namespace std;
const int maxs = 1e4;
int main(){

    string str[maxs],a,b;
    int now=0;
    while(getline(cin,str[++now])&&str[now]!="end");//每次输入文本的一行,直到回车终止
    //注意这里用++now,而不用now++,因为now++之后,str[now]永远是下一个位置,所以一直不能终止
    getline(cin,a);
    getline(cin,b);
    int pos;//position
    for(int i=0;i<now;i++){
        while((pos=str[i].find(a))!=-1){
            //printf("%d\n",pos);//看看被替换词在本句中的位置,返回首个字母的位置
            str[i].replace(pos,a.size(),b);//把a.size()大小的位置用b来替换
        }
    }
    for(int i=0;i<now;i++){
        cout << str[i] << endl;
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值