The difference between the BUG version and the BUG-free version is: In the freCount() of the BUG-free version, the char array "word" is directly defined instead of being read in through the fgets().
BUG version: (if you enter the main string as "domanmanman", the result is 1)
#include<stdio.h>
#include<string.h>
#define MAX 3000
int main(){
char str[MAX];
printf("Enter the text:\n");
fgets(str, sizeof(str), stdin);
freCount(str);
}
void freCount(char* str) {
int cntWord = 0;
char word[MAX];
printf("Enter the string you want to count:\n");
fgets(word, sizeof(word), stdin);
for (int j = 0; j <= strlen(str) - strlen(word); j++) {
int k;
for (k = 0; k < strlen(word); k++) {
if (str[j + k] != word[k])
break;
}
if (k == strlen(word)) {
cntWord++;
k = 0;
}
}
printf("The frequency of the string is:%d\n", cntWord);
}
BUG-free version:
#include<stdio.h>
#include<string.h>
#define MAX 3000
void freCount(char* str);
int main(){
char str[MAX];
printf("Enter the text:\n");//To facilitate testing, please enter "domanmanman"
fgets(str, sizeof(str), stdin);
freCount(str);
return 0;
}
void freCount(char* str) {
int cntWord = 0;
char word[MAX] = { "man" };
for (int j = 0; j <= strlen(str) - strlen(word); j++) {
int k;
for (k = 0; k < strlen(word); k++) {
if (str[j + k] != word[k])
break;
}
if (k == strlen(word)) {
cntWord++;
k = 0;
}
}
printf("The frequency of the string is:%d\n", cntWord);
}