首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

C++ 字符串插入實現:std::string::insert 一行搞定

     編輯:程式設計疑難解答

題目要求

輸入字符串 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,安全、高效、可讀性強。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved