Search code examples
cstringcpu-word

C - How to count exact word in a string? (exluding the times the word is inside of another)


I'm making a program which reads from stdin or from a file and counts number of if statements. I've done it but if for example I have a variable called "asdifasd" or "ifasd" it shall be counted as an if statement. How do I extract solely the if-statements? Here's my code:

char str[150];
int ifs = 0;

while (fgets(str, sizeof(str), stdin) != NULL)
    {
        char *p = str;
        while (((p = (strstr(p, "if"))) != NULL)) {
            ifs++;
            ++p;
        }
    }

I've been thinking about doing something with strncmp but I'm not sure how.


Solution

  • After you've found "if" using strstr, check the characters immediately before and after to make sure they're not a letter. Like:

    {
      char *p = str;
      while (((p = (strstr(p, "if"))) != NULL)) {
        if ((p == str || !isalnum((unsigned char) p[-1])) &&
             !isalnum((unsigned char) p[2]))
          ++ifs;
        ++p;
      }
    }