P5734 【深基6.例6】文字处理软件
题目描述
你需要开发一款文字处理软件。最开始时输入一个字符串作为初始文档。可以认为文档开头是第 0 个字符。需要支持以下操作:
1 str:后接插入,在文档后面插入字符串 str \texttt{str} str,并输出文档的字符串。
2 a b:截取文档部分,只保留文档中从第 a 个字符起 b 个字符,并输出文档的字符串。
3 a str:插入片段,在文档中第 a 个字符前面插入字符串 str \texttt{str} str,并输出文档的字符串。
4 str:查找子串,查找字符串 str \texttt{str} str 在文档中最先的位置并输出;如果找不到输出 −1。
为了简化问题,规定初始的文档和每次操作中的 str \texttt{str} str 都不含有空格或换行。最多会有 q 次操作。
输入格式
第一行输入一个正整数 q,表示操作次数。
第二行输入一个字符串 str \texttt{str} str,表示最开始的字符串。
第三行开始,往下 q 行,每行表示一个操作,操作如题目描述所示。
输出格式
一共输出 n 行。
对于每个操作 1 , 2 , 3 1,2,3 1,2,3,根据操作的要求输出一个字符串。
对于操作 4,根据操作的要求输出一个整数。
输入输出样例
输入
4
ILove
1 Luogu
2 5 5
3 3 guGugu
4 gu
输出
ILoveLuogu
Luogu
LuoguGugugu
3
代码如下
#include<iostream>
#include<string>
using namespace std;
int main(){
string str,s; //str原始字符,s为输入字符
int q,temp,l,r; //q为操作次数,temp用来存放对应序号操作 l代表截取位置 ,r为截取长度
cin>>q>>str;
for(int i=1; i<=q; i++){
cin>>temp;
if(temp==1){
cin>>s;
str += s; //str.append(s) 在str后连接字符
cout<<str<<endl;
}
else if(temp==2){
cin>>l>>r;
str=str.substr(l,r);
//s.substr(pos,len)截取字符串s从第pos个位置开始r个字符,并返回这个字符串
cout<<str<<endl;
}
else if(temp==3){
cin>>l>>s;
str=str.insert(l,s);