The solution is strtok() in string.h.
Here's a good example of how to use.
/* strtok example by [email protected]
*
* This is an example on string tokenizing
*
* 02/19/2002
*
* http://www.metalshell.com
*
*/
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
int x = 1;
char str[]="this:is:a:test:of:string:tokenizing";
char *str1;
/* print what we have so far */
printf("String: %s\n", str);
/* extract first string from string sequence */
str1 = strtok(str, ":");
/* print first string after tokenized */
printf("%i: %s\n", x, str1);
/* loop until finishied */
while (1)
{
/* extract string from string sequence */
str1 = strtok(NULL, ":");
/* check if there is nothing else to extract */
if (str1 == NULL)
{
printf("Tokenizing complete\n");
exit(0);
}
/* print string after tokenized */
printf("%i: %s\n", x, str1);
x++;
}
return 0;
}
The thing that confuses people about strtok is the first time you call the method the first argument you pass in a pointer to the string you want to tokenize and on subsequent calls you pass NULL. strtok uses a static variable in it's implementation to keep track of where it should start start searching from in subsequent calls.
- Passing NULL you're telling strtok to continue searching from where we left off last time.
- Passing in a pointer != NULL you're telling the tokenizer that you are starting at the beginning of a new string so disregard previous state information.