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 64 65 66 67 68 69 70 71 72 73 74 75 76 77
|
#include "extreme.h"
/******************************************************
* strparse *
* *
* Takes a pointer to a string and a delimiter *
* and a pointer to an integer to split string *
* by with delimiter delimiter. *
* *
* Returns a pointer to a two dimensional *
* array of the split parts and sets the *
* integer to the number of split parts. *
* *
******************************************************/
char **strparse(char *string, const char *delim, int *numsecs) {
char *data[MAX_SECTIONS];
char **sections;
char **ret;
char *ptr;
char *lastptr;
int delimlen;
int idx;
int len;
int delimsfound = 0;
int partlen = 0;
delimlen = strlen(delim);
len = strlen(string);
sections = data;
ret = data;
ptr = string;
for (idx = 0; idx < len; idx++) {
if (delimsfound > MAX_SECTIONS)
return ret;
if (strncmp(string + idx, delim, delimlen) == 0) {
if (delimsfound == 0) {
lastptr = string;
} else {
partlen -= delimlen;
lastptr = ptr - partlen;
}
if (partlen == 0)
*sections = NULL;
else {
if ((*sections = malloc(partlen)) == NULL) {
errno = ENOMEM;
return NULL;
}
strncpy(*sections, lastptr, partlen);
}
partlen = 0;
delimsfound++;
sections++;
}
partlen++;
ptr++;
}
if (idx == len) {
if (partlen == 0)
*sections = NULL;
else {
if ((*sections = malloc(partlen)) == NULL) {
errno = ENOMEM;
return NULL;
}
partlen -= delimlen;
strncpy(*sections, ptr - partlen, partlen);
}
}
*numsecs = delimsfound + 1;
if ((*data = realloc(*data, *numsecs * sizeof(char *))) == NULL) {
errno = ENOMEM;
return NULL;
}
return ret;
}
|