跳到正文

题解

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

#SUSPENDED#约 5 分钟
原文
文章信息与版本

文章信息

发布
2025年7月1日
收录
2025年12月12日
更新
2026年11月18日
篇幅
约 5 分钟
题目
P5734

版本

  1. v1当前

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

题目分析

我们需要实现一个简单的文字处理软件,支持四种操作:

  1. 后接插入字符串
  2. 截取子字符串
  3. 在指定位置插入字符串
  4. 查找子字符串位置

解题思路

我们可以直接使用C++的string类来处理这些操作,因为它已经内置了这些功能的实现。

四种操作分别是这样的

操作1:后接插入

C++
if (op == 1) {
    string str;
    cin >> str;
    doc += str; // 使用+=运算符拼接字符串
    cout << doc << endl;
}
  • 公式:doc=doc+strdoc = doc + str
  • 将输入字符串str追加到doc末尾

操作2:截取子串

C++
else if (op == 2) {
    int a, b;
    cin >> a >> b;
    doc = doc.substr(a, b); // 截取子串
    cout << doc << endl;
}
  • 公式:doc=substr(doc,a,b)doc = substr(doc, a, b)
  • 保留从位置a开始的b个字符

操作3:指定位置插入

C++
else if (op == 3) {
    int a;
    string str;
    cin >> a >> str;
    doc.insert(a, str); // 在位置a前插入
    cout << doc << endl;
}
  • 公式:doc=insert(doc,a,str)doc = insert(doc, a, str)
  • 在位置a前插入字符串str

操作4:查找子串

C++
else if (op == 4) {
    string str;
    cin >> str;
    size_t pos = doc.find(str);
    if (pos != string::npos) {
        cout << pos << endl;
    } else {
        cout << -1 << endl;
    }
}
  • 公式:pos=find(doc,str)pos = find(doc, str)
  • 查找str在doc中首次出现的位置,找不到返回-1

最后贴上完整代码代码

!温馨提示:珍爱生命,拒绝抄袭

C++
#include <iostream>
#include <string>
using namespace std;
int main() {
    int q;
    string doc;
    cin >> q >> doc; // 读取操作次数和初始字符串
    while (q--) {
        int op;
        cin >> op;
        if (op == 1) {
            // 操作1:后接插入
            string str;
            cin >> str;
            doc += str; // 字符串拼接
            cout << doc << endl;
        } else if (op == 2) {
            // 操作2:截取子串
            int a, b;
            cin >> a >> b;
            doc = doc.substr(a, b); // 从a开始截取b个字符
            cout << doc << endl;
        } else if (op == 3) {
            // 操作3:在指定位置插入
            int a;
            string str;
            cin >> a >> str;
            doc.insert(a, str); // 在位置a前插入str
            cout << doc << endl;
        } else if (op == 4) {
            // 操作4:查找子串
            string str;
            cin >> str;
            size_t pos = doc.find(str); // 查找子串位置
            if (pos != string::npos) {
                cout << pos << endl;
            } else {
                cout << -1 << endl;
            }
        }
    }
    return 0;
}

复杂度分析

  • 时间复杂度:O(q×n)O(q \times n),其中nn是字符串的平均长度
  • 空间复杂度:O(n)O(n),存储字符串所需空间

总结

本题主要考察对字符串基本操作的理解和实现,使用C++的string类可以大大简化代码实现。关键在于熟练掌握字符串的拼接、截取、插入和查找操作。

原文