Skip to content

Instantly share code, notes, and snippets.

@forestbelton
Created April 6, 2013 03:32
Show Gist options
  • Save forestbelton/5324637 to your computer and use it in GitHub Desktop.
Save forestbelton/5324637 to your computer and use it in GitHub Desktop.
string splitting in C (a la PHP's explode())
char **strsplit(const char *s, int delim) {
int state;
char *sout;
char **out;
size_t i, count, word;
/* Skip any leading delimiters. */
while(*s == delim)
++s;
/* Count the number of words in the string. */
state = 1;
count = 0;
for(i = 0; s[i] != 0; ++i) {
/* Flip into state 1 (delimiter skip state). */
if(s[i] == delim && state == 0)
state ^= 1;
/* Flip into state 0 (word skip state). */
else if(s[i] != delim && state == 1) {
state ^= 1;
++count;
}
}
/* Allocate pointer for each word and a NULL terminator. */
out = malloc((count + 1) * sizeof *out);
if(out == NULL)
return NULL;
/* Make a copy of the input. */
sout = malloc(i + 1);
/* Set pointers in string array. */
state = 1;
word = 0;
while(*s) {
if(*s == delim && state == 0) {
state ^= 1;
*sout++ = 0;
}
if(*s != delim) {
if(state != 0) {
state ^= 1;
out[word++] = sout;
}
*sout++ = *s;
}
++s;
}
/* Add NULL terminator. */
out[word] = NULL;
return out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment