南京华瑞杰自动化设备公司的一道笔试题目,要求用 C 写一个函数,实现查找一个单词在一句英文里面出现的次数
,不区分大小写
函数原型如下:int find(const char * line,const char *word);
当时没做出来,回来写了一个,但还是不太满意,很多没考虑到,比如连续空格,逗号判断,逗号加空格等,由于没有办法处理双引号,只好先过滤掉双引号,默认英文为标准的一句英文,没有连续空格,呵呵,基本实现了。
期待高人指正
/* find words */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
int findwords(const char * line,const char * word);
char *p="This is an /"example/" about how to find words in a string";
char *word="example";
printf("%s /n",p);
printf("find %d /n",findwords(p,word));
}
/* 过虑字符*/
void filter(char *p,char x)
{
int n=strlen(p);
int i,j;
i=j=0;
while(i<n)
{
if(*(p+i)==x)
{
for(j=i;j<n;j++)
*(p+j)=*(p+j+1);
}
i++;
}
}
int findwords(const char * line,const char * word)
{
int n=0;
int Lc=0; //表示当前单词的长度
int Byte=sizeof(*word); //一个字符的字节
int LL=strlen(line);
int Lw=strlen(word);
char *h,* p,*q;
h=malloc((LL+1)*sizeof(*line));
strcpy(h,line);
*(h+LL)='/0';
q=p=h;
filter(h,'/"'); //过滤掉双引号
while(*q !='/0')
{
if(*q==32) //找到一个空格,
{
Lc=(q-p)/Byte; //计算出当前单词的长度
if(Lc==Lw) //仅仅在长度相等时才比较
{
char *t=malloc((Lc+1)*sizeof(*word));
strncpy(t,p,Lc); //把以p指针开头长度为当前长度的单词复制到临时字符串t中
*(t+Lc)='/0'; //最后一位 置反斜杠零
if(strcasecmp(t,word)==0) // strcasecmp函数忽略大小写比较,相等时返回 0
{
/*printf("find one : %s/n",t); 可以打印出来验证*/
n++;
}
free(t); //释放临时空间
t=NULL;
}
p=q+1;
/*q指向空格,将q指向的下一个位赋值给p,直到q再次找到下一个空格为止,
这样p--q-1之间就是一个完整的单词,但这个时刻q指向的是一个空格
*/
Lc=0; //把单词长度归零
}
q++;
}
free(h);
h=p=q=NULL;
return n;
}