2017-03-09 89 views
0

我想知道一个数字出现在从文件读取的字符串中出现了多少次,但我无法解决我的问题。计算字符串中出现的次数

这里是我的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

对于初学者来说,'while(equal!= NULL){'因为'equal'在循环中没有变化,所以有一个无限循环。这就是为什么“短分支”在“长”之前走的最好例子 - 最后浮出来的“无法打开文件”消息简直令人困惑! – John3136

+1

值得你花时间阅读[this](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong),并使用['fgets'](https:/ /linux.die.net/man/3/fgets)而不是'gets' – yano

回答

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; 
} 
+1

这是正确的。不知道你为什么被低估。 – Mdjon26

+0

@ Jay266你改变了我的所有程序ahahaha,但它运作完美。非常感谢你。 8小时的工作浪费:(我是这个新的。 – Bernat

+0

@Bernat你能给我的答案一个复选标记吗?:) – Jay266

相关问题