]> git.neil.brown.name Git - metad.git/blob - strsplit.c
Assorted reformating
[metad.git] / strsplit.c
1 #include <malloc.h>
2 #include <string.h>
3 #include <stdio.h>
4
5 /*
6  * split a string into an array of strings,
7  * separated by any chars in the fs string
8  * strings may contain chars from fs if quoted
9  * quotes may be escaped or quoted
10  *
11  * MWR, UNSW, Oct 84
12  */
13
14 char **
15 strsplit(char *s, char *fs)
16 {
17         char            *sp, *sp2, *delim, **ssp, *ns;
18         unsigned        i, num;
19         static char             quote[] = "'";
20
21         if((ns = malloc((unsigned) strlen(s) + 1)) == NULL)
22                 return NULL;
23         sp = s;
24         sp2 = ns;
25         num = 0;
26         while(*sp)
27         {
28                 while(*sp && strchr(fs, *sp))
29                         sp++;
30                 if(!*sp)
31                         break;
32
33                 num++;
34                 do
35                 {
36                         delim = fs;
37                         while(*sp && !strchr(delim, *sp))
38                         {
39                                 switch(*sp)
40                                 {
41                                 case '\'':
42                                 case '"':
43                                         if(delim == fs)
44                                         {
45                                                 quote[0] = *sp++;
46                                                 delim = quote;
47                                                 continue;
48                                         }
49                                         break;
50                                 case '\\':
51                                         if(sp[1] == '\'' || sp[1] == '"')
52                                                 sp++;
53                                         break;
54                                 }
55                                 *sp2++ = *sp++;
56                         }
57                         if(delim == quote && *sp)
58                                 sp++;
59                 }
60                 while(delim == quote && *sp);
61                 *sp2++ = '\0';
62         }
63
64         if((ssp = (char **) malloc(sizeof(char *) * (num + 2))) == NULL)
65                 return NULL;
66         sp = ns;
67         ssp[0] = ns;
68         for(i = 1; i <= num; i++)
69         {
70                 ssp[i] = sp;
71                 while(*sp)
72                         sp++;
73                 sp++;
74         }
75         ssp[i] = NULL;
76         return &ssp[1];
77 }