码迷,mamicode.com
首页 > 其他好文 > 详细

字符串翻转和替换

时间:2018-03-25 17:02:23      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:strong   替换   --   需要   out   iostream   test   字符串翻转   post   

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

输入:多组数据,以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;
}

 

字符串翻转和替换

标签:strong   替换   --   需要   out   iostream   test   字符串翻转   post   

原文地址:https://www.cnblogs.com/xym4869/p/8645003.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!