题目:输入两个字符串,从第一字符串中删除第二个字符串中所有的字符。 例如,输入”They are students.”和”aeiou”,则删除之后的字符串变成”Thy r stdnts.”。
分析:题目可分解为如何判断一个字符串中包含特定字符以及如何在一个字符串中删除特定字。
判断一个字符串是否包含是定字符
可首先创建一个字符Hash表,字符为key,值为1代表字符串2包含这个字符,值为0代表不包含。
删除指定字符
一个比较好的方法是通过快慢消除法,一个快指针,一个慢指针都指向字符串1地址,快指针用来控制循环,而慢指针负责跨过字符串2中出现的字符。
具体实现如下:
#include <stdio.h>
#define Boolean int
#define TRUE 1
#define FALSE 0
int charHash[256] = {0};
void createCharHash(const char *s)
{
while(*s)
{
charHash[*s++] = 1;
}
}
Boolean isContain(char c)
{
if(charHash[c])
{
return TRUE;
}else{
return FALSE;
}
}
void delChars(char *str, const char *s)
{
int i = 0;
int j = 0;
createCharHash(s);
while(str[i])
{
if(!isContain(str[i]))
{
str[j++] = str[i];
}
i++;
}
str[j] = '\0';
}
int main(void)
{
char xie[] = "They are students.";
delChars(xie, "aeiou");
printf("result is %s\n",xie);
return 0;
}