Home > Enterprise >  Problem with my function in C when trying to find a string in a text file
Problem with my function in C when trying to find a string in a text file

Time:12-27

I am trying to check the existance of a string in my text file, I already wrote a function that transforms my file content into a string.

char*read(FILE*f);

the function I wrote to find String is:

int find(FILE* f, char* M){
   char*chaine=read(f);

  
   if(strstr(chaine, M)!=0){
    
    printf("\n Word exists");
    return 0;
   }
   printf("\nThe word doesn't exist!!");
     return -1;
   
}

Example of a text file:

Hey I am a beginner C learner.

when I try with the word "He" it says that the word exists.

CodePudding user response:

strstr() is finding the string He because those characters are found in Hey. You can try using isalpha() on the character after to see if it's the end of the word or if you've found a match within another word.

Here is an example of using isalpha() and strlen() if a match is found with strstr().

char *example = "Hey I am a beginner C learner.";
char *ia_example = "He, I am a beginner C learner.";

char *to_find = "He";

char *match;

if ((match = strstr(example, to_find)) && !isalpha(match[strlen(to_find)])) {
    printf("\"%s\" found in example: \"%s\"\n", to_find, example);
}

if ((match = strstr(ia_example, to_find)) && !isalpha(match[strlen(to_find)])) {
    printf("\"%s\" found in ia_example: \"%s\"\n", to_find, ia_example);
}

Output:

"He" found in ia_example: "He, I am a beginner C learner."

strlen() is used to get the length of the substring you are searching for (in this case He) which will be length 2. So match[strlen(to_find)] (ie match[2]) will be the character directly after the matched substring. If you put that character into isalpha() and it returns false, then you know the character following your substring match is not any char a-z or A-Z.

This will ensure that you're not finding a match in the middle of a word, like you did with "Hey". Do note this code example doesn't take into account checking that the substring appears at the end of a word. So you would need to perform a similar check on the character before the match to see whether or not that isalpha()

  • Related