split.c (1056B)
1 #include <stdlib.h> 2 3 /* split buf into n strings that are separated by c. return n as *len. 4 * Allocate plus more slots and leave the first ofs of them alone. */ 5 char **split(char *buf,int c,size_t* len,size_t plus,size_t ofs) { 6 int n=1; 7 char **v=0; 8 char **w; 9 /* step 1: count tokens */ 10 char *s; 11 for (s=buf; *s; s++) if (*s==c) n++; 12 /* step 2: allocate space for pointers */ 13 v=(char **)malloc((n+plus)*sizeof(char*)); 14 if (!v) return 0; 15 w=v+ofs; 16 *w++=buf; 17 for (s=buf; ; s++) { 18 while (*s && *s!=c) s++; 19 if (*s==0) break; 20 if (*s==c) { 21 *s=0; 22 *w++=s+1; 23 } 24 } 25 *len=w-v; 26 return v; 27 } 28 29 #ifdef UNITTEST 30 #include <assert.h> 31 #include <string.h> 32 #include <stdio.h> 33 34 int main() { 35 char inp[]="foo\nbar\nbaz"; 36 size_t len; 37 char** x=split(inp, '\n', &len, 2, 1); 38 assert(len==4 && !strcmp(x[1],"foo") && !strcmp(x[2],"bar") && !strcmp(x[3],"baz") && x[4]==NULL); 39 free(x); 40 char inp2[]="fnord"; 41 x=split(inp2, '\n', &len, 2, 1); 42 assert(len==2 && !strcmp(x[1],"fnord") && x[2]==NULL); 43 return 0; 44 } 45 #endif