Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to count tokens in C?

I'm using strtok to split a string into tokens. Does anyone know any function which actually counts the number of tokens?

I have a command string and I need to split it and pass the arguments to execve() .

Thanks!

Edit

execve takes arguments as char**, so I need to allocate an array of pointers. I don't know how many to allocate without knowing how many tokens are there.

like image 458
James Avatar asked Oct 25 '12 23:10

James


1 Answers

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) ...
like image 151
nneonneo Avatar answered Oct 10 '22 04:10

nneonneo