Created
April 6, 2013 03:32
-
-
Save forestbelton/5324637 to your computer and use it in GitHub Desktop.
string splitting in C (a la PHP's explode())
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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