题解:P5734 【深基6.例6】文字处理软件
Submerge__l · · 题解
P5734 【深基6.例6】文字处理软件
题目分析
我们需要实现一个简单的文字处理软件,支持四种操作:
- 后接插入字符串
- 截取子字符串
- 在指定位置插入字符串
- 查找子字符串位置
解题思路
我们可以直接使用C++的string类来处理这些操作,因为它已经内置了这些功能的实现。
四种操作分别是这样的
操作1:后接插入
if (op == 1) {
string str;
cin >> str;
doc += str; // 使用+=运算符拼接字符串
cout << doc << endl;
}
- 公式:
doc = doc + str - 将输入字符串
str追加到doc末尾
操作2:截取子串
else if (op == 2) {
int a, b;
cin >> a >> b;
doc = doc.substr(a, b); // 截取子串
cout << doc << endl;
}
- 公式:
doc = substr(doc, a, b) - 保留从位置
a开始的b个字符
操作3:指定位置插入
else if (op == 3) {
int a;
string str;
cin >> a >> str;
doc.insert(a, str); // 在位置a前插入
cout << doc << endl;
}
- 公式:
doc = insert(doc, a, str) - 在位置
a前插入字符串str
操作4:查找子串
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) - 查找
str在doc中首次出现的位置,找不到返回-1最后贴上完整代码代码
!温馨提示:珍爱生命,拒绝抄袭
#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 \times n) ,其中n 是字符串的平均长度 - 空间复杂度:
O(n) ,存储字符串所需空间
总结
本题主要考察对字符串基本操作的理解和实现,使用C++的string类可以大大简化代码实现。关键在于熟练掌握字符串的拼接、截取、插入和查找操作。