top1编程
← 返回题目
题解

【入门】查找子串并替换

1 条题解

  • 0
    @ 2026-7-31 5:01:51

    解题思路

    题目要求将字符串中的某个子串替换为另一个子串。

    用 string 的 find 找到子串位置,再用 replace 替换即可。注意要查找所有出现的位置,替换后继续往后找。

    参考代码

    #include <iostream>
    #include <string>
    using namespace std;
    
    int main() {
        string s, a, b;
        getline(cin, s);
        getline(cin, a);
        getline(cin, b);
    
        int pos = s.find(a);
        while (pos != -1) {
            s.replace(pos, a.size(), b);
            pos = s.find(a, pos + b.size());
        }
        cout << s << endl;
        return 0;
    }
    

    复杂度分析

    • 时间复杂度:O(N×M),N 为原串长度,M 为子串长度
    • 空间复杂度:O(1)
    • 1