I write a strsplit function which converts a string separated by a delimeter to a sub-string array.
If anyone can give some advice to optimize it, or raise some new thought about this implementation? Tkx.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char * const *strsplit(char *p, char sep)
{
if (p == NULL)
return NULL;
int num = 0;
int i = 0;
char **arry = NULL;
char **newarrybuff;
char *strcur;
char *tmpstr = malloc(strlen(p) + 1);
if (!tmpstr)
return NULL;
strcur = tmpstr;
strcpy(tmpstr, p);
while (strcur) {
if (*strcur == sep) {
strcur++;
continue;
}
newarrybuff = realloc(arry, sizeof(char*) * (i+1));
if (!newarrybuff) {
free(arry);
return NULL;
}
arry = newarrybuff;
arry[i++] = strcur;
strcur = strchr(strcur, sep);
if(strcur)
*strcur++ = '\0';
}
newarrybuff = realloc(arry, sizeof(char*) * (i+1));
if (!newarrybuff) {
free(arry);
return NULL;
}
arry = newarrybuff;
arry[i++] = NULL;
newarrybuff = realloc(arry, sizeof(char*) * (i+1));
if (!newarrybuff) {
free(arry);
return NULL;
}
arry = newarrybuff;
arry[i++] = tmpstr;
return arry;
}
void strsplitfree(char * const *p)
{
if (!p) return;
char * const *tmp = p;
while (*tmp++);
free(*tmp);
free((void*)p);
}
int main(int argc, char **argv)
{
char str[] = "::::hello::wold:";
char * const *s = strsplit(str, ':');
int j=0;
if (s == NULL)
return 1;
for (j = 0; s[j] != NULL; j++) {
printf("%s\n", s[j]);
}
strsplitfree(s);
return 0;
}