题解:P5734 【深基6.例6】文字处理软件

· · 题解

‌这题十分简单但只有2篇题解……‌
那就由蒟蒻我来补充一下吧(有表述不当处欢迎大家指出)

‌题意:‌完成 q 次字符串处理,共四种:

‌思路:‌这四种处理都包含在 STL 的函数中,可以直接用。

函数 作用
append() 在字符串末尾添加内容
substr() 返回从指定位置开始的子字符串
insert() 在指定位置插入内容
find() 查找子字符串在字符串中的位置

‌注意:‌find()函数若没找到,返回的是string::npos,不是 -1,需要判断。

代码实现


#include<bits/stdc++.h>
using namespace std;
int q,x;
string s;
int main(){
    cin>>q>>s;
    for(int i=1;i<=q;i++){
        cin>>x;
        if(x==1){
            string str;
            cin>>str;
            s.append(str);
        }
        else if(x==2){
            int a,b;
            cin>>a>>b;
            s=s.substr(a,b);
        }
        else if(x==3){
            int a;
            string str;
            cin>>a>>str;
            s=s.insert(a,str);
        }
        else if(x==4){
            string str;
            cin>>str;
            if(s.find(str)==string::npos) cout<<-1<<endl;
            else cout<<s.find(str)<<endl;
            continue;
        }
        cout<<s<<endl;
    }
    return 0;
}