69,382
社区成员
发帖
与我相关
我的任务
分享
/* counting the presence of a word in a text file */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
#define LEN 41
#define MAX 256
void to_Upper(char *); //将string中的字母全部变成大写
int main(void)
{
char wordtofind[LEN];
char wordinfile[LEN];
char tempcap[LEN]; //用作复制一份wordtofind串,然后将其中的首字母变大写
char tempupper[LEN]; //同上,然后用作将其中的所有字母变大写
char filename[MAX];
char *wif = wordinfile;
int ch;
long count;
bool state;
FILE * fp;
puts("Input a word to count (empty line to quit):");
while(gets(wordtofind) != NULL && wordtofind[0] != '\0')
{
count = 0;
state = false;
puts("Input the name of the file to search the word in:");
gets(filename);
if((fp = fopen(filename, "r")) == NULL)
{
fprintf(stderr, "Error opening %s", filename);
exit(EXIT_FAILURE);
}
while((ch = getc(fp)) != EOF)
{
if(isalpha(ch))
{
state = true;
*wif++ = ch; //装载wordinfile串
}
if((isspace(ch) || ispunct(ch)) && state == true)
{
*wif = '\0'; //完成wordtofile串
strcpy(tempcap, wordtofind);
strcpy(tempupper, wordtofind);
to_Upper(tempupper);
tempcap[0] = toupper(tempcap[0]);
if(strcmp(wordtofind, wordinfile) == 0 ||
strcmp(tempcap, wordinfile) == 0 ||
strcmp(tempupper, wordinfile) == 0)
count++; //在file中发现了相同的串即计数
state = false;
wif = wordinfile; //再次初始化wif
}
}
fclose(fp);
printf("%s found %ld %s.\n",
wordtofind, count, (count > 1)? "times" : "time");
puts("Input a word to count (empty line to quit):");
}
puts("Done!");
system("PAUSE");
return 0;
}
void to_Upper(char *str)
{
while(*str)
*str++ = toupper(*str);
}