輸入字符串 S1、S2 與位置 n(1-based),在 S1 第 n 個字符前插入 S2。例:S1="jiangsu", S2="123", n=3 → "ji123angsu"。
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1, s2;
int pos;
while (cin >> s1 >> s2 >> pos) {
if (pos >= 1 && pos <= s1.length() + 1) {
s1.insert(pos - 1, s2); // insert 參數為 0-based 索引
cout << s1 << endl;
} else {
cerr << "Invalid position" << endl;
}
}
return 0;
}
string::insert(pos, str) 在 pos 位置插入 str,pos 為 0-based,故傳入 pos-1。pos == s1.length()+1(即插入到末尾),insert 內部會處理邊界。while(cin >> s1 >> s2 >> pos) 支持多組測試數據,EOF 結束。若不允許用 string,需用 char[] 手動騰挪:
char s1[200], s2[100];
int n;
cin.getline(s1, 200);
cin.getline(s2, 100);
cin >> n;
int len1 = strlen(s1), len2 = strlen(s2);
// 從後向前移動數據,騰出 len2 空間
for (int i = len1; i >= n; --i) s1[i + len2] = s1[i];
// 複製 s2
for (int i = 0; i < len2; ++i) s1[n + i] = s2[i];
cout << s1 << endl;
生產代碼首選 std::string,安全、高效、可讀性強。