Michel Wervers
Michel Wervers

Reputation: 33

Using substrings to count the number of times a word appears

I want to use substrings to count the number of times a specific word has been typed in. I have been playing with my code a little to see if I could make it work but I just don't get it!

My code is the following:

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

int main(int argc, char *argv[])
{

int i=0;

char buf[1026]={'\0'};
char *p="#EOF\n";
char *t;

while (strcmp(buf, p) != 0)
{
    fgets(buf, 1025, stdin);
    t=strtok(buf," , - \n");
    while(t != NULL)
    {
        if(strncmp(t, argv[1], strlen(argv[1])) == 0)
    {
        i++;
    }
    }
}






printf("%d\n", i);

return 0;
}

There are no errors, but the value of i is always 0. I don't know how to make sure it keeps counting after it finds the word once. I tried sizeof(t) < j, but that doesn't work.

Upvotes: 1

Views: 368

Answers (2)

Paul Rubel
Paul Rubel

Reputation: 27222

If you're looking for more than one instance of the token you need to call strtok multiple times. On subsequent calls pass in NULL as the first argument. See the man page

Also, sizeof(t) is a constant, probably 4 or 8. t is a char pointer, it takes up some amount of bytes. If you're looking to see if strtok returned something you want to compare against NULL. From the man page:

RETURN VALUE

  The strtok() and strtok_r() functions return a pointer 
   to the next token, or  NULL  if there are no more tokens.

The NULL is what you want to check for to determine that there are no more tokens on that line.

Also note that if a token bridges two reads, you won't get it. For example line 1 ends with " ," and the next ready starts with "- \n"

Upvotes: 2

Brendan Long
Brendan Long

Reputation: 54242

while(sizeof(t) > j)

sizeof tells you the size of a type, so in your case, it's sizeof(char*), which is just the size of a pointer on your platform. Most likely it's always 4 or 8. Replace it with strlen, which is designed to tell you the size of a string.

Upvotes: 0

Related Questions