Skip to content

Instantly share code, notes, and snippets.

@pamolloy
Created June 21, 2012 16:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pamolloy/2966810 to your computer and use it in GitHub Desktop.
Save pamolloy/2966810 to your computer and use it in GitHub Desktop.
Parsing strings with multiple delimiters
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *sep[] = {";", "=", ":", ",", NULL};
char string[] = "entertitle=uncollapse,grabkeys;"
"enterslave=grabkeys;leaveslave=collapse,ungrabkeys;"
"button1=menuexec;button2=togglestick;button3=exit:13;"
"button4=scrollup;button5=scrolldown;"
"key_Up=scrollup;key_Down=scrolldown;"
"key_Escape=ungrabkeys,exit";
int split( char *input, int i )
{
char *token;
char *remain; // Remainder of string to be parsed
// For the first call to strtok: token != NULL && token == input
token = strtok_r(input, sep[i], &remain);
printf(" %s\n", token);
while(token != NULL) {
/* Inefficient because terminates after all delimiters
were checked. Too many calls to strtok() */
if (sep[i+1] != NULL) {
split(token, i+1);
}
token = strtok_r(NULL, sep[i], &remain);
if (token != NULL)
printf("%s\n", token);
}
}
int main()
{
split(string, 0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment