Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strstr whole string match

Tags:

c

string

I'm trying to match the whole string and not just part of it. For instance, if the needle is 2, I would like to match just the string 2 and not 20, 02, or 22 or anything related.

I'm using strstr as:

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{
   FILE *file;
   char l[BUFSIZ];
   int linenumber = 1;
   char term[6] = "2";

   file = fopen(argv[1], "r");
   if(file != NULL) {
      while(fgets(l, sizeof(l), file)){
         if(strstr(l, term) != NULL) {
             printf("Search Term Found at %d!\n", linenumber);
         }
         ++linenumber;
      }
   }
   else {
      perror(argv[1]);
   }

   fclose(file);
   return 0;
}
like image 854
clay Avatar asked Nov 23 '25 14:11

clay


2 Answers

Use strcmp instead of strstr or, for a better answer, define "anything related".

like image 137
convex hull Avatar answered Nov 26 '25 03:11

convex hull


strstr is matching the string "2". If you don't want it to match things where 2 is combined with other things, you're going have to define exactly what "just the string 2" means. Is it 2 surrounded by whitespace?

I'm guessing what you really want to do is to tokenize the input (perhaps delimited on whitespace or something) and then check whether a token is the string "2". (In that case, use strtok and strcmp.)

like image 43
jamesdlin Avatar answered Nov 26 '25 03:11

jamesdlin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!