计算字符串中出现的次数

标签 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 出现两次。我怎样才能做到这一点?

最佳答案

我会把它分解,这样它就不会全部在 main 方法中。这将计算该字符串在此方法中出现的次数。

#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;
}

关于计算字符串中出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42706553/

相关文章:

c++ - 简明、精确的 WordNet 教程?

c - 指向 union 函数的指针

java - 识别字符串中的大写字母及其位置

r - 计算R中每组连续连续值的长度

Mysql - 根据条件计算连续日期并获取范围列表

mysql - 计算患者(女性和男性)第一次咨询的次数以及随后的咨询次数

c - 如何在c中将unsigned char *转换为unsigned int *?

c - 是否可以在一个 long int 变量中存储 2 个 32 位值?

python:如何在一次搜索中找到\r\n\r\n

javascript如何删除字符串的某一部分?