#include #include #include #define STRING "1\n2\n3\n4\n5\n6\n7" static char **gnokii_strsplit(const char *string, const char *delimiter, int tokens) { const char *left = string; char *tmp, *str; int count = 0; char **strings; if (!string || !delimiter || !tokens) return NULL; strings = NULL; while ((tmp = strstr(left, delimiter)) != NULL) { if (tokens > 0 && count == tokens) break; str = malloc((tmp - left) + 1); memset(str, 0, (tmp - left) + 1); memcpy(str, left, tmp - left); /* +3 = * +1 for the current string * +1 for the remainder * +1 for the null termination */ strings = realloc(strings, sizeof(char *) * (count + 3)); printf ("setting strings[%d] to %s\n", count, str); strings[count] = str; left = tmp + strlen(delimiter); count++; } strings[count] = strdup(left); strings[count+1] = NULL; for (count = 0; count < tokens; count++) { printf("strings[%d] = %s\n", count, strings[count]); } return strings; } static void gnokii_strfreev (char **strings) { int i; for (i = 0; strings[i] != NULL; i++) free (strings[i]); free (strings); } int main (int argc, char **argv) { char **lines; int i; lines = gnokii_strsplit (STRING, "\n", -1); for (i = 0; lines[i] != NULL; i++) printf ("line %d: %s\n", i, lines[i]); gnokii_strfreev (lines); return 0; }