#include #include #include /* * Split a string into parts given a single separator character, * If we have a string: aaa|bb|c, and split by '|', then the result * will be: [['a','a','a','\0'], ['b','b','\0'], ['c','\0']]. * Note: for simplicity, this function splits by only a single char */ char **split_by_char(const char x, const char *s) { char **parts; int i, n, nc, len = strlen(s), content_length = 0, num_parts = 1; /* Figure out how many parts we will split s into. I was lazy and didn't feel like making a more optimized version by putting this elsewhere. */ for(i = 0; i < len-1; i++) { if(s[i] == x) { num_parts++; /* skip multiple adjacent separators */ for (; i < len-1 && s[i] == x; i++) ; } content_length++; } /* allocate row pointers */ if((parts = (char **) malloc(sizeof(char *) * num_parts)) == NULL) { printf("Could not allocate space for the parts array."); exit(1); } /* Separate the string and allocate col pointers */ i = 0; /* Go through the split sections */ for(n = 0; n < num_parts; n++) { nc = 1; /* allocate no space */ parts[n] = (char *) calloc(0, sizeof(char)); for(; i < len; i++, nc++) { if(s[i] == x) break; /* make space to push a char onto the array */ parts[n] = (char *) realloc(parts[n], sizeof(char) * nc); parts[n][nc - 1] = s[i]; } /* add a null character to the string */ parts[n] = (char *) realloc(parts[n], sizeof(char) * (nc+1)); parts[n][nc] = '\0'; /* increment the char count past the separator */ i++; } return parts; } int main() { char **parts = split_by_char('|', "aaaa|bbb|cc"); int i, len = sizeof(parts); for(i = 0; i < len; i++) { printf("%s\n", parts[i]); } return 0; }