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

C++ 字符串替換實現:從基礎版到交互式 Word 風格替換

     編輯:程式設計綜合問答

需求分析

  • 主函數輸入原文、查找串、替換串。
  • 調用 replace(char* text, char* s, char* t) 實現全文替換。
  • 高級:交互式替換,找到匹配詢問用戶「繼續查找(F)」或「替換(R)」。

基礎版:全量替換

#include 
#include 
#include 

// 返回替換次數
int replace(char* text, const char* s, const char* t) {
    if (!text || !s || !t || !*s) return 0;

    int count = 0;
    size_t s_len = strlen(s);
    size_t t_len = strlen(t);
    char* pos = text;

    while ((pos = strstr(pos, s)) != NULL) {
        // 計算尾部剩餘長度
        size_t tail_len = strlen(pos + s_len);
        // 如果替換串更長,需擴容(這裡假設 text 空間足夠大,實際應動態分配)
        memmove(pos + t_len, pos + s_len, tail_len + 1); // 含 '\0'
        memcpy(pos, t, t_len);
        count++;
        pos += t_len; // 移過替換串,避免重複匹配重疊部分
    }
    return count;
}

int main() {
    char text[1024] = {0};
    char s[100], t[100];

    printf("輸入原文: ");
    fgets(text, sizeof(text), stdin);
    text[strcspn(text, "\n")] = '\0'; // 去換行

    printf("輸入查找串: ");
    fgets(s, sizeof(s), stdin);
    s[strcspn(s, "\n")] = '\0';

    printf("輸入替換串: ");
    fgets(t, sizeof(t), stdin);
    t[strcspn(t, "\n")] = '\0';

    int n = replace(text, s, t);
    printf("替換次數: %d\n", n);
    printf("結果: %s\n", text);
    return 0;
}

進階版:交互式替換(模擬 Word)

int replaceInteractive(char* text, const char* s, const char* t) {
    if (!text || !s || !t || !*s) return 0;

    int count = 0;
    size_t s_len = strlen(s);
    size_t t_len = strlen(t);
    char* pos = text;
    char choice;

    while ((pos = strstr(pos, s)) != NULL) {
        printf("\n找到匹配 @ 位置 %ld: ...%.20s...\n", pos - text, pos);
        printf("替換(R) / 繼續查找(F) / 退出(Q): ");
        scanf(" %c", &choice); // 空格吃掉殘留換行
        while (getchar() != '\n'); // 清緩衝區

        if (choice == 'Q' || choice == 'q') break;
        if (choice == 'R' || choice == 'r') {
            size_t tail_len = strlen(pos + s_len);
            memmove(pos + t_len, pos + s_len, tail_len + 1);
            memcpy(pos, t, t_len);
            count++;
            pos += t_len;
        } else { // 'F' 或其他
            pos += s_len; // 跳過本次匹配
        }
    }
    return count;
}

關鍵技術點

函數用途
strstr查找子串首次出現位置
memmove安全移動內存(處理重疊區域)
memcpy複製替換串到目標位置
scanf(" %c", ...)讀取單字符,前置空格跳過空白字符

注意事項

  1. 緩衝區溢出風險:若替換後字符串超過原 text 容量會越界。生產代碼應使用動態內存(realloc)或 std::string。
  2. 重疊匹配:替換後指針前移 t_len 而非 s_len,避免在剛替換的文本中再次匹配(如將 "a" 替換為 "aa")。
  3. 輸入處理:fgets 讀取整行,需手動去除尾部換行符。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved