计算字符串中出现的次数

时间:2017-03-09 22:17:57

标签: c string count

我想知道从文件中读取的字符串中有多少次出现,但我无法解决问题。

这是我的C代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(){
   int MAX_MEM = 100000, i, count=0;
   char string[MAX_MEM];
   char search[MAX_MEM];
   FILE *fp;
   fp = fopen("prova1000.txt", "r");

   if (fp != NULL) {

       while (!feof(fp)){
           fread(string, sizeof(string), MAX_MEM, fp);
           printf("%s",string);
           char search[MAX_MEM];
           printf("\nEnter the number to search:");
           gets(search);
           char *equal = strstr(string,search);
           if(equal!= NULL){
               printf("The number introduced is in the list\n");
               while(equal!=NULL){
                  count++;
                  printf("The number is %d times\n", count);
               }
          }
          else{
              printf("The number introduced is not in the list\n");
           }
         }
     }

     else 
          printf("Couldn't open the file");

     return 0;
     fclose(fp);
  }

prova1000.txt是这样的:

100000000000000
100000000000001
100000000000001
100000000000003
100000000000004
100000000000005
100000000000006
100000000000007
100000000000008
...

例如,我想在计数中显示100000000000001出现两次。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

我会分手,所以主要方法并不是全部。这将计算此方法中该字符串的出现次数。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int wc(char* file_path, char* word){
    FILE *fp;
    int count = 0;
    int ch, len;

    if(NULL==(fp=fopen(file_path, "r")))
        return -1;
    len = strlen(word);
    for(;;){
        int i;
        if(EOF==(ch=fgetc(fp))) break;
        if((char)ch != *word) continue;
        for(i=1;i<len;++i){
            if(EOF==(ch = fgetc(fp))) goto end;
            if((char)ch != word[i]){
                fseek(fp, 1-i, SEEK_CUR);
                goto next;
            }
        }
        ++count;
        next: ;
    }
end:
    fclose(fp);
    return count;
}

int main(){//testestest : count 2
    char key[] = "test"; // the string I am searching for
    int wordcount = 0;

    wordcount = wc("input.txt", key);
    printf("%d",wordcount);
    return 0;
}