我想知道一个数字在从文件读取的字符串中出现了多少次,但我无法解决我的问题。
这是我的 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/