✔ 最佳答案
Here is a C++ source program which will count the number of occurrences of a given word in a given file.
The usage is
occur file-name word
The link to a text file of the source is:
http://mathmate.brinkster.net/
and the program source is:
/* occur.cpp - displays the number of times a word or phrase appears in a text.
NOTE: The word to be counted is case sensitive.
If case insensitivity is required, use toupper() to convert
all words to upper case before comparison.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
if(argc<3)
{
printf("Usage: occur fileName wordOrPhrase\n");
printf("Example: occur textfile good\n");
exit(0);
}
FILE *f1=fopen(argv[1],"r");
if(f1==NULL)
{
printf("File %s does not exist. Please try again\n");
exit(0);
}
char li[200]; // max. line length of 200 characters
int count=0;
while((fgets(li,199,f1))!=NULL)
{
char *p=strtok(li," ,.!?;");
do
{
// p is the token delimited by any of space,.!? or ;
// argv[2] is the string to be counted
if(strcmp(p,argv[2])==0)count++;
}while((p=strtok(NULL," ,.!?;"))!=NULL);
}
printf("%s occurred %d times in the given text\n",argv[2],count);
return 0;
}