© 2026 黄瀚轩 GitHub ↗
写作 / All notes

天梯赛模拟题:字符串的剪切与粘贴

一道字符串模拟题的 C++ 实现,记录剪切、定位、插入和边界处理。

来自旧站 · 2024—2026
原文迁移到新站,保留内容与公式,排版与题图做了重新整理。作者:黄瀚轩。

这道题把「剪切板」建模成一个字符串操作问题:先从原串截取一段,再在剩余字符串里寻找前后缀锚点,最后把剪贴板内容插回去。原始题面截图已随旧站迁移移除,下面保留实现。

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str;
    cin >> str;
    int N;
    cin >> N;

    for (int i = 0; i < N; i++) {
        int start, end;
        string front, back;
        cin >> start >> end >> front >> back;

        // 1. 剪切
        string clipboard = str.substr(start - 1, end - start + 1);
        str.erase(start - 1, end - start + 1);

        // 2. 粘贴
        string target = front + back;
        size_t pos = str.find(target);
        if (pos != string::npos) {
            // 找到,插在 front 后面
            pos += front.length();
        } else {
            // 没找到,插在最后
            pos = str.length();
        }
        str.insert(pos, clipboard);
        // 操作完成后剪贴板应被清空(题目要求),虽然下次循环会被覆盖,但逻辑上可体现。
    }

    cout << str << endl;
    return 0;
}
END / 黄瀚轩 · 2026.02.23