P5734 【深基6.例6】文字处理软件[c++版]

题目链接

https://www.luogu.com.cn/problem/P5734
传送门

题目描述

你需要开发一款文字处理软件。最开始时输入一个字符串(不超过 100 个字符)作为初始文档。可以认为文档开头是第 0 个字符。需要支持以下操作:

1 str:后接插入,在文档后面插入字符串 str,并输出文档的字符串。

2 a b:截取文档部分,只保留文档中从第 a 个字符起 b 个字符,并输出文档的字符串。

3 a str:插入片段,在文档中第 a 个字符前面插入字符串 str,并输出文档的字符串。

4 str:查找子串,查找字符串 str 在文档中最先的位置并输出;如果找不到输出 -1。

为了简化问题,规定初始的文档和每次操作中的 str 都不含有空格或换行。最多会有 (q≤100) 次操作。

输入格式

输出格式

输入输出样例

输入 #1

4
ILove
1 Luogu
2 5 5
3 3 guGugu
4 gu

输出 #1

ILoveLuogu
Luogu
LuoguGugugu
3

提示

自己写函数或者直接使用STL!
本题用到的STL:
substr 生成子串,输入位置和长度

insert 在字符串中插入字符串

find 查找字符串中某个字符串的位置并返回它的位置

代码

#include<iostream>
#include<string>
using namespace std;
int main(){

    int n;
    string str;
    cin >> n >> str;
    for(int i = 0;i <n;i++){
        int temp;
        cin >> temp;
        switch(temp){
            case 1:{
                string str1;
                cin >> str1;
                str = str + str1;//或者使用 str.append(str1);
                cout << str << endl;
                break;
            }
            case 2:{
                int a,b;
                cin >> a >> b;
                str = str.substr(a,b);//截取str中从a开始的b个字符
                cout << str << endl;
                break;
            }
            case 3:{
                int a;
                string str1;
                cin >> a >>str1;
                str.insert(a,str1);//在str的第a个位置插入str1
                cout << str <<endl;
                break;
            }
            case 4:{
                string str1;
                cin >> str1;
                int a = str.find(str1);//在str中寻找str1的位置
                cout << a << endl;
            }
        }
    }
    return 0;
}

版权声明:本文为ElleMuyi原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。