#include #include #include /** * Note: The returned array must be malloced, assume caller calls free(). */ char** splitWordsBySeparator(char** words, int wordsSize, char separator, int* returnSize) { struct { char **data; unsigned long cap; unsigned long size; } ret = {0}; char buf[21] = {0}; ret.cap = wordsSize; for ( int i = 0; i < wordsSize; ++i ) { char *cstr = words[i]; while ( *cstr != '\0' ) { ret.cap += ( *cstr == separator ); ++cstr; } } ret.data = malloc((ret.cap+1) * sizeof(*ret.data)); memset(ret.data, 0, (ret.cap+1) * sizeof(*ret.data)); ret.size = 0; for ( int i = 0; i < wordsSize; ++i ) { unsigned long wsize = 0; char *cstr = words[i]; while ( *cstr != '\0' ) { if ( *cstr == separator ) { ++cstr; if ( wsize == 0 ) { continue; } ret.data[ret.size] = calloc(wsize + 1, sizeof(char)); memcpy(ret.data[ret.size], buf, wsize); ++ret.size; wsize = 0; continue; } buf[wsize++] = *cstr; ++cstr; } if ( wsize == 0 ) { continue; } ret.data[ret.size] = calloc(wsize + 1, sizeof(char)); memcpy(ret.data[ret.size], buf, wsize); ++ret.size; } *returnSize = ret.size; return ret.data; } void r(char **ws, int s, char sep) { int ret_size = 0; char **retorig = splitWordsBySeparator(ws, s, sep, &ret_size); printf("RetSize = %d\n", ret_size); if ( retorig == NULL ) return; char **ret = retorig; printf("Ret = ["); while ( *ret != NULL ) { printf("\"%s\", ", *ret); free(*ret++); } printf("]\n"); free(retorig); } int main(void) { char *words[] = {"one.two.three","four.five","six"}; r(words, 3, '.'); return 0; }