C 練習實例32
題目:刪除一個字串中的指定字母,如:字串 "aca",刪除其中的 a 字母。
程式分析:無。
實例
// Created by www.xuhuhu.com on 15/11/9.
//
//
#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