只是简单调试了下,有问题你再找我。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define maxLength 1000
void main()
{
int count = 0,len = 0;
FILE *fp;
char *in;
char *serch;
char *ret = NULL;
char tou, wei;
char *s = (char *)malloc(maxLength);
in = (char *)malloc(maxLength);
memset(s, 0, maxLength);
fp = fopen("test.txt", "r+");
if (fp == NULL)
{
printf("open file failed\n");
return;
}
fgets(s, maxLength, fp);
s = _strlwr(s); //转换成小写
fclose(fp);
printf("read file success %s\n",s);
printf("请输入单词:\n");
scanf("%s",in);
in = _strlwr(in); //转换成小写
len = strlen(in);
serch = s;
while (1)
{
ret = strstr(serch, in);
if (ret != 0)
{
/* 单词的头和尾是空格或者, */
tou = *(ret - 1);
wei = *(ret + len);
//printf("%c %c", *(ret - 1), *(ret + len));
if (((ret == s) || (tou == ' ') || ((tou == ',')))
&& ((wei == ' ') || (wei == '.') || (wei == ',')))
{
count++;
}
serch = ret + len;
}
else
{
break;
}
}
printf("%s出现的次数是%d次\n",in, count);
}