本實例實現通用字符刪除函數:根據字符集 charSet 從字符串 str 中刪除所有屬於該集合的字符。
hash,標記需刪除字符(ASCII 碼為下標)。currentIndex 指向寫入位置,遍歷原字符串,若字符不在刪除集則寫入並前移。currentIndex 處添加 '\0' 截斷。// Created by www.runoob.com on 15/11/9.
// Copyright © 2015年 菜鳥教程. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* deleteCharacters(char *str, char *charSet) {
int hash[256];
if (NULL == charSet) return str;
for (int i = 0; i < 256; i++) hash[i] = 0;
for (int i = 0; i < strlen(charSet); i++)
hash[charSet[i]] = 1;
int currentIndex = 0;
for (int i = 0; i < strlen(str); i++) {
if (!hash[str[i]])
str[currentIndex++] = str[i];
}
str[currentIndex] = '\0';
return str;
}
int main() {
char s[2] = "a";
char s2[5] = "aca";
printf("%s\n", deleteCharacters(s2, s));
return 0;
}
c
O(n+m) 時間,O(1) 額外空間(固定 256 整數),原地修改,支持任意字符集刪除。