I have a string that looks like 1,3-5,7,9-11 and I'm to tokenize it with repeated calls to strtok so that the output looks something like:
1
3
5
7
9
11
My code looks like this:
#include <stdio.h>
#include <string.h>
void tokenize(char *string){
char *token;
token = strtok (string,"-");
while (token != NULL) {
// ... do some other unrelated stuff ...
printf("\tToken %s\n", token);
token = strtok (NULL, ",");
}
}
int main (int argc,char **argv)
{
char *token;
token = strtok (*(argv+1),",");
while (token != NULL) {
if (strchr(token,45)){ //45 is ASCII for "-".
tokenize(token);
}
printf("Token1 %s \n", token);
token = strtok (NULL, ",");
}
return 0;
}
However, when I run the code it ends prematurely and I get:
./tokenizer 1,3-5,7,9-11
Token1 1
Token 3
Token 5
Token1 3
but I expect/want something like:
./tokenizer 1,3-5,7,9-11
Token1 1
Token 3
Token 5
Token1 7
Token 9
Token 11
If I comment out the line that reads tokenize(temptoken);
(in other words, strtok on "," only), then the output looks like one would expect:
./tokenizer 1,3-5,7,9-11
Token1 1
Token1 3-5
Token1 7
Token1 9-11
So it looks like the problem really is with the subsequent strtok calls to the already tokenized string so I tried to memcpy memory pointed to be the token pointer but that didn't really help:
#include <stdio.h>
#include <string.h>
void tokenize(char *string){
char *token;
token = strtok (string,"-");
while (token != NULL) {
printf("\tToken %s\n", token);
token = strtok (NULL, ",");
}
}
int main (int argc,char **argv)
{
char *token;
char *temptoken ;
token = strtok (*(argv+1),",");
while (token != NULL) {
if (strchr(token,45)){ //45 is ASCII for "-".
/* added memcpy */ memcpy(temptoken,token,strlen(token)+1);
tokenize(temptoken);
}
printf("Token1 %s \n", token);
token = strtok (NULL, ",");
}
return 0;
}
$ ./tokenizer 1,3-5,7,9-11
Token1 1
Token 3
Token 5
Token1 3-5
Any ideas of what I can do to fix the code, understand where my misunderstanding lies, and get the desired output?