#include<stdio.h> #include<assert.h> #include<malloc.h> #include<memory.h> void Delete_specific_char(char * str1, char * str2) { char * phash = (char *)malloc(sizeof(char)*256); assert(phash); memset(phash, 0, 256); int i = 0; while(str2[i] != '\0' ) { phash[str2[i++]] =1; } int newp = 0; i = 0; while(str1[i] != '\0' ) { if(phash[str1[i]] ==1) { i++; } str1[newp++] = str1[i]; i++; } str1[newp ] ='\0'; free(phash); } int main() { char a1[] = "they are student."; char a2[] = "aeiou"; Delete_specific_char(a1, a2); printf("%s",a1); printf("%s\n",a2); return 0 ; }
#include <stdio.h> #include <malloc.h> #include <assert.h> #include <memory.h> void Delete_specific_char(char * str1, char * str2) { assert(str1); assert(str2); char * phash = ( char * )malloc( sizeof(char)*256 );//先將str2在phash中映射一遍 memset(phash,0,256); int i = 0; while ( str2[i] != '\0') { phash[str2[i]] = 1; i++; } char * fast = str1; //這個指針用來掃描str1 char * slow = str1; //這個指針用來修改str1,存放的是下一個待修改的位置 int j = 0; while (fast[j]!= '\0') //開始掃描str1 { if (phash[*fast] != 1) //如果fast所指向的字母在str2中沒有,fast,slow就都指向下一個 { *slow =*fast; fast++; slow++; } else //如果fast所指向的字母在str2中存在,那麼fast指向下一個 { fast++; while (phash[*fast])//繼續掃描,把連續的在str2中的字符都跳過,直到找到一個非str2中的字符 { fast++; } *slow = *fast; //將那個非str2的字符賦給slow當前所指向的字符 slow++; //繼續掃描, fast++; } } *slow = '\0'; free(phash); } int main( ) { char a1[] = "they are student. "; char a2[] = "aeiouac"; Delete_specific_char(a1, a2); int i = 0; while (a1[i] !='\0') { printf("%c",a1[i]); i++; } printf(":\n"); return 0; }