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

· · 题解

传送门

思路:

这道题所有的操作均可使用 <string.h> 头文件中的库函数来完成。需要使用这三个库函数:

同时,<string.h> 也重载了运算符:+=。

+= 与 .append() 库函数的用法是一样的,都是在指定字符串的后面插入新的字符串。

实现:

首先写出整体的代码框架,包括输入与判断(谁都会):

#include<bits/stdc++.h>
using namespace std;
int main(){
    string s;
    int n;
    cin>>n>>s;
    for(int i=0;i<n;i++){
        int cz;
        cin>>cz;//不是chen_zhe,是“操作” 
        switch (cz){
            case 1:{

                break;
            }
            case 2:{

                break;
            }
            case 3:{

                break;
            }
            case 4:{

                break;
            }
        }
    }
    return 0;
}

这道题最难的部分在于 4 个操作:

string tmp;
cin>>tmp;
s+=tmp;
cout<<s<<'\n';
int a,b;
cin>>a>>b;
s=s.substr(a,b);
cout<<s<<'\n';
int a;
string tmp;
cin>>a>>tmp;
s.insert(a,tmp);
cout<<s<<'\n';
string tmp;
cin>>tmp;
int a=s.find(tmp);
if(a==(int)string::npos){
cout<<-1<<'\n';
}
else{
cout<<a<<'\n';
}

最后附上全部代码:

#include<bits/stdc++.h>
using namespace std;
int main(){
    string s;
    int n;
    cin>>n>>s;
    for(int i=0;i<n;i++){
        int cz;
        cin>>cz;//不是chen_zhe 
        switch (cz){
            case 1:{
                string tmp;
                cin>>tmp;
                s+=tmp;
                cout<<s<<'\n';
                break;
            }
            case 2:{
                int a,b;
                cin>>a>>b;
                s=s.substr(a,b);
                cout<<s<<'\n';
                break;
            }
            case 3:{
                int a;
                string tmp;
                cin>>a>>tmp;
                s.insert(a,tmp);
                cout<<s<<'\n';
                break;
            }
            case 4:{
                string tmp;
                cin>>tmp;
                int a=s.find(tmp);
                if(a==(int)string::npos){
                    cout<<-1<<'\n';
                }
                else{
                    cout<<a<<'\n';
                }
                break;
            }
        }
    }
    return 0;
}