After the initial call to
strtok()
you can pass
NULL
as the first parameter and strtok will use the previously supplied string buffer to return the next string.
word1 = strtok(str, ",");
word2 = strtok(NULL, ",");
word3 = strtok(NULL, ",");
if( toFind == '0') {
printf("%s\n", word1);
}
or perhaps, more usually:
char *words[3];
i = 0;
for(word = strtok(str, ","); word != NULL; word = strtok(NULL, ",") {
words[i++] = word;
}
int whichWord = atoi(toFind);
whichWord -= 1;
printf("%s\n", words[whichWord];
Note that if we need to increase the number of fields, all we need to do is to change
char *words[3]
to maybe
char *words[10]
. We could even dynamically allocate the variable
words
by counting the commas in the input string and then use a call to
malloc()
to create the needed space.
Be aware that
strtok()
modifies the input buffer, so you must not use a
const char
, as this will almost certainly cause a runtime error. Also, since the input buffer is modified, if you need to re-parse the input buffer, in this case, it will have all commas replaced with nul chars ('\0'). In that case, you might want to make a copy of the original input buffer, perhaps using
strdup()