首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C >> 關於C

C 語言實現:從字串中刪除指定字元集合

     編輯:關於C

需求:從字串 A 中移除所有出現在字串 B 中的字元。採用「查找表 + 原地壓縮」演算法,時間複雜度 O(n+m),空間 O(1)(固定 256 位元組查找表)。

核心函數

void deleteChars(char* dest, const char* charsToRemove) {
    int lenDest = strlen(dest);
    int lenChars = strlen(charsToRemove);
    
    // 建立字元查找表
    int lookup[256] = {0};
    for (int i = 0; i < lenChars; ++i) {
        lookup[(unsigned char)charsToRemove[i]] = 1;
    }
    
    // 原地壓縮:讀寫雙指針
    int writeIdx = 0;
    for (int readIdx = 0; readIdx < lenDest; ++readIdx) {
        if (!lookup[(unsigned char)dest[readIdx]]) {
            dest[writeIdx++] = dest[readIdx];
        }
    }
    dest[writeIdx] = '\0';  // 重新終止字串
}

測試主程式

int main() {
    char a[] = "hello world";
    char b[] = "ewd";
    printf("Before: %s\n", a);
    deleteChars(a, b);
    printf("After : %s\n", a);  // 輸出: hllo worl
    return 0;
}

演算法優勢

  • 單遍歷:讀寫指針同步推進,無需巢狀迴圈搬移資料。
  • 原地修改:不額外分配記憶體,適合嵌入式環境。
  • 完整處理:使用 unsigned char 索引避免負值越界,支援完整 ASCII/擴展字元集。

擴充建議

若需 Unicode 支援,可改用 wchar_t 並配合 std::unordered_set 或排序後二分搜尋,但會增加記憶體開銷。

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