/************************************************************************ 5.4面试例题 删除特定字符 用C语言编写一个高效率的函数用于删除字符串里给定的字符。这个函数的模型如下 void removeChars(char str[], char remove[]); 注意,remove里的所有字符都必须从str中删干净。比如说:
str是"Battle of the Vowels: Haweii vs. Grozny"; remove是"aeiou";
这个函数将把str转化为"Bttl f th Vwls: Hw vs. Grzny"
************************************************************************/
#include <stdio.h> #include <stdlib.h>
#define MAX_CHARS 256 void removeChars(char str[], char remove[]) { int src, dist, removeArray[MAX_CHARS]; for (src = 0; src < MAX_CHARS; src++) { removeArray[src] = 0; } src = 0; while (remove[src] != ‘\0‘) { removeArray[remove[src]] = 1; src++; }
src = dist = 0; do { if (removeArray[str[src]] == 0) { str[dist++] = str[src]; } } while(str[src++] != ‘\0‘); }
int main() { char str[] = "Battle of the Vowels: Haweii vs. Grozny"; char remove[] = "aeiou";
removeChars(str, remove); int i = 0; for (i = 0; str[i] != ‘\0‘; i++) { printf("%c", str[i]); } return 0; }
|