如何在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:
- Find the starting position of substring
bwithinstrusingfind(). - Verify the substring exists (to avoid invalid operations if
bisn't instr). - Calculate the insertion point: since we want to insert after
b, the position isstarting position of b + length of b. - 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 ofstr). - 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
bappears multiple times instr,find()will only locate the first occurrence. If you need to insert after every instance ofb, 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 >> bwithgetline(cin, a)andgetline(cin, b)(make sure to handle any leftover newline characters from previous inputs if needed).
内容的提问来源于stack exchange,提问作者Gerald Sihotang
相关产品推荐
相关产品推荐

