字符串翻转和替换

描述:大家平时都会用到字符串,现在有几种字符串操作,需要你用这几种操作处理下字符串。

输入:多组数据,以EOF结束。

第一行一个字符串,字符串长度大于0,并且小于等于200。

第二行一个数字t,(0<t<=200)。

下面t行,每行表示一种操作。

共有两种操作,每行数据的第一个数表示操作的种类:

翻转操作:第一个是一个数字0,然后两个数字i和len,翻转从下标i长度为len的子串。

替换操作:第一个是一个数字1,然后两个数字i和len,接着一个长度为len的字符串str,用str替换从下标i长度为len的子串。

字符串操作后会更新,旧的字符串被舍弃。

 

两种解决方式,一种是使用replace函数,但这种方式会超时啊。。。另一种。。。emmm,就用原始方式就很好。。。

 

#include <iostream>
#include<cstdio>
#include<string.h>
#define N 200
using namespace std;

int main()
{
    string str;
    cin>>str;
    int t;
    cin>>t;
    while(t--){
        string testr=str;
        int op,i,len;
        scanf("%d %d %d",&op,&i,&len);
    if(op==0){
        string temp;
        for(int j=i+len-1;j>=i;j--){
            temp+=str[j];
        }
        testr.replace(i,len,temp);
    }
    if(op==1){
        string temp;
        cin>>temp;
        testr.replace(i,len,temp);
    }
    cout<< testr<<endl;
    }
    return 0;
}

 

#include <iostream>
#include<string.h>
using namespace std;

int main()
{
    string str;
    cin >> str;
    int t;
    cin >> t;
    while(t--){
        int op,i,len;
        scanf("%d %d %d",&op,&i,&len);
        string testr=str;
        if(op==0){
            for(int j=i+len-1,k=i;j>=i&&k<i+len;j--,k++){
                    testr[k]=str[j];
            }
        }
        else if(op==1){
            string temp;
            cin >> temp;
            for(int j=i,k=0;j<i+len &&k<len;j++,k++){
                    testr[j]=temp[k];
            }
        }
        cout<<testr<<endl;
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/xym4869/p/8645003.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值