blob: 456de87a5fe86a4365f054d0867a83a793c6037a (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
#include <string.h>
#include <stdlib.h>
/* Like strsep(3) except that the delimiter is a string, not a set of characters.
*/
char *strstrsep(char **stringp, const char *delim) {
char *match, *save;
save = *stringp;
if (*stringp == NULL)
return NULL;
match = strstr(*stringp, delim);
if (match == NULL) {
*stringp = NULL;
return save;
}
*match = '\0';
*stringp = match + strlen(delim);
return save;
}
static char **words = NULL;
static int max_words;
char **split(char *s, const char *delim, int *pn) {
int i;
char *tok, *rest;
if (words == NULL) {
max_words = 10;
words = malloc(max_words*sizeof(char *));
}
i = 0;
rest = s;
while ((tok = (delim ? strstrsep(&rest, delim) : strsep(&rest, " \t\n"))) != NULL) {
if (!delim && !*tok) // empty token
continue;
while (i+1 >= max_words) {
max_words *= 2;
words = realloc(words, max_words*sizeof(char *));
}
words[i] = tok;
i++;
}
words[i] = NULL;
if (pn != NULL)
*pn = i;
return words;
}
inline int isspace(char c) {
return (c == ' ' || c == '\t' || c == '\n');
}
char *strip(char *s) {
int n;
while (isspace(*s) && *s != '\0')
s++;
n = strlen(s);
while (n > 0 && isspace(s[n-1])) {
s[n-1] = '\0';
n--;
}
return s;
}
|