123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- #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;
- }
|