题目
牛客网-BUPT 2011 网研 ProblemA
读入一组字符串(待操作的),再读入一个int n记录记下来有几条命令,总共有2种命令:
1、翻转 从下标为i的字符开始到i+len-1之间的字符串倒序;
2、替换 命中如果第一位为1,用命令的第四位开始到最后的字符串替换原读入的字符串下标 i 到 i+len-1的字符串。每次执行一条命令后新的字符串代替旧的字符串(即下一条命令在作用在得到的新字符串上)。
命令格式:第一位0代表翻转,1代表替换;第二位代表待操作的字符串的起始下标int i;第三位表示需要操作的字符串长度int len。
输入描述
输入有多组数据。
每组输入一个字符串(不大于100)然后输入n,再输入n条指令(指令一定有效)。
输出描述
根据指令对字符串操作后输出结果。
示例
输入
bac
2
003
112as
输出
cab
cas
题解
用c++的库函数搞定
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
//翻转
void reverse(string &s,string cmd)
{
int start=cmd[1]-'0';
int l=cmd[2]-'0';
string sub=s.substr(start,l);//截取要翻转的子串sub
reverse(sub.begin(),sub.end());//翻转sub
s.replace(start,l,sub);//用翻转后的sub替换原sub
}
//替换
void replace(string &s,string cmd)
{
int start=cmd[1]-'0';
int l=cmd[2]-'0';
string subs=cmd.substr(3);//替换的字符串
s.replace(start,l,subs);//替换
}
int main()
{
int n;
string s;
while(cin>>s>>n)
{
string cmd;//指令
for(int i=0;i<n;i++)
{
cin>>cmd;
if(cmd[0]=='0')
reverse(s,cmd);
else
replace(s,cmd);
cout<<s<<endl;
}
}
}
改进
替换部分直接利用reverse函数,而不用取子串,翻转,替换
这一系列操作
然后,因为代码也不多,直接在main里写替换和翻转更简洁,就不用子函数了
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
int n;
string s;
while(cin>>s>>n)
{
string cmd;//指令
for(int i=0;i<n;i++)
{
cin>>cmd;
int start=cmd[1]-'0';
int l=cmd[2]-'0';
if(cmd[0]=='0')
reverse(s.begin()+start,s.begin()+start+l);
else
{
string subs=cmd.substr(3);//替换的字符串(cmd从3开始到末尾)
s.replace(start,l,subs);//替换
}
cout<<s<<endl;
}
}
}
小结
题目中用到的还不太熟的函数
1. algorithm 中 reverse()
//翻转s[start]到s[start+len-1]
reverse(s.begin()+start,s.begin()+start+len);
//翻转整个s字符串
reverse(s.begin(),s.end());
2. string 中 substr()
多与s.find("RandomString")
一起用
//截取从start开始长度为len的子串
s.substr(start,len);
//截取从start开始到末尾的子串
s.substr(start);
3. string 中 replace()
//用"RandomString"替换s中从start开始长度为len的子串
s.replace(start,len,"RandomString");