You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C++中实现子串后插入指定字符串?

How to Insert String a Right After Substring b in str

Hey there! The issue with your current code is that the std::string::insert method doesn't work the way you're using it—you can't directly pass the substring b as the insertion position. Let's fix this step by step.

The Correct Approach

To insert a right after b in str, you need to:

  1. Find the starting position of substring b within str using find().
  2. Verify the substring exists (to avoid invalid operations if b isn't in str).
  3. Calculate the insertion point: since we want to insert after b, the position is starting position of b + length of b.
  4. Perform the insertion using the correct insert() overload.

Full Working Code Example

#include <iostream>
#include <string>

using namespace std;

int main() {
    string a, b, str;
    // Note: If your strings contain spaces, use getline instead of cin!
    cin >> a >> b;
    // Set the example str you provided
    str = "ihaveadream";
    
    // Step 1: Find the position of b in str
    size_t pos = str.find(b);
    
    // Step 2: Check if b was found
    if (pos != string::npos) {
        // Step 3 & 4: Insert a right after b
        str.insert(pos + b.length(), a);
        cout << "Result: " << str << endl;
    } else {
        cout << "Substring '" << b << "' not found in the target string." << endl;
    }
    
    return 0;
}

Testing Your Example Scenario

For your input:

  • a = "simple"
  • b = "ihavea"
  • str = "ihaveadream"

The code will:

  • Find pos = 0 (since "ihavea" starts at the beginning of str).
  • Calculate insertion position as 0 + 6 (length of "ihavea" is 6).
  • Insert "simple" at index 6, resulting in ihaveasimpledream—exactly what you want!

Key Notes

  • If b appears multiple times in str, find() will only locate the first occurrence. If you need to insert after every instance of b, you'll need to loop through the string and repeat the insertion logic (adjusting the position each time to account for the newly inserted characters).
  • If your strings might contain whitespace, replace cin >> a >> b with getline(cin, a) and getline(cin, b) (make sure to handle any leftover newline characters from previous inputs if needed).

内容的提问来源于stack exchange,提问作者Gerald Sihotang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:57:50