您的位置:首页 > 其它

从第一字符串中删除第二个字符串中所有的字符

2013-09-01 02:39 411 查看
题目:输入两个字符串,从第一字符串中删除第二个字符串中所有的字符。

例如,输入”They are students.”和”aeiou”,则删除之后的字符串变成”Thy r stdnts.”。

分析:题目可分解为如何判断一个字符串中包含特定字符以及

如何在一个字符串中删除特定字。

判断一个字符串是否包含是定字符,可首先创建一个字符串的Hash表,把字符串中对应的字符对代表的hash元素置为1. 字符参数所代表Hash元素值是为1就表示字符存在。

(这种“字符串hash”的思想要掌握,可以快速在一些字符中查找某个字符)

在一个字符串中删除指定字符,比较好的方法是通过快慢消除法。

具体实现如下:

#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; //这里默认会进行integral promotion整形提升,所以不需要显示(int)转化

}

}

Boolean isContain(char c)

{

if(charHash[c])

{

return TRUE;

}else{

return FALSE;

}

}

void delChars(char *str, const char *s)//str是要操作的字符,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;

}


当我在写上面的程序时,代码如下;

char * delChars(char *s,const char* s2)
{
createTable(s2);

char *source=s;
int j=0;
while(*s)
{
if(hashTable[*s]==0)
{
s[j++]=*s;

}
s++;
}
s[j]='\0';
}


总是运行错误,debug了好久,终于找出错在哪里了。

s[j++]=*s;

这里错误,我们的j是相对于原来的起点的,这里s已经移动了,不是原来的起点。改正:

void delChars(char *s,const char* s2)
{
createTable(s2);

char *source=s;
int j=0;
while(*s)
{
if(hashTable[*s]==0)
{
//s[j++]=*s 错误
source[j++]=*s;
}
s++;
}
source[j]='\0';

}


转自;http://blog.163.com/xie_wenbin613/blog/static/17548909520125133138852/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐