Is there a way to count tokens in C?
One approach would be to simply use strtok
with a counter. However, that will modify the original string.
Another approach is to use strchr
in a loop, like so:
int count = 0;
char *ptr = s;
while((ptr = strchr(ptr, ' ')) != NULL) {
count++;
ptr++;
}
If you have multiple delimiters, use strpbrk
:
while((ptr = strpbrk(ptr, " \t")) != NULL) ...
As number of tokens is nothing but one more than the frequency of occurrence of the delimiter used. So your question boils down to find no. of times of occurrence of a character in a string
say the delimiter used in strtok function in c is ' '
int count =0,i;
char str[20] = "some string here";
for(i=0;i<strlen(str);i++){
if(str[i] == ' ')
count++;
}
No. of tokens would be same as count+1