#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "explode.h"
struct array *explode(char *string, char *separator, int copy) {
int i, len, seplen;
char *ptr;
struct array *array;
int slots = 5;
int elems = 1;
len = strlen(string);
seplen = strlen(separator);
array = malloc(sizeof(struct array));
if (!array) {
return NULL;
}
array->size = 0;
array->vector = (char **)malloc(sizeof(char *) * slots);
if (!array->vector) {
free(array);
return NULL;
}
if (copy) {
array->copy = ISCOPY;
array->slot = (char *)malloc(len + 1);
if (!array->slot) {
free(array->vector);
free(array);
return NULL;
}
memcpy(array->slot, string, len);
array->slot[len] = 0;
} else {
array->copy = NOCOPY;
array->slot = string;
}
ArrayElem(array, 0) = array->slot;
ptr = array->slot;
for (i = 0; i < (len - seplen + 1);) {
if (memcmp(ptr + i, separator, seplen) == 0) {
elems++;
if (elems >= slots) {
char **tmp;
slots = slots * 2;
tmp = (char **)realloc(array->vector, sizeof(char *) * slots);
if (tmp) {
array->vector = tmp;
} else {
free(array->slot);
free(array->vector);
free(array);
return NULL;
}
}
memset(ptr + i, 0, seplen);
ArrayElem(array, ++array->size) = ptr + i + seplen;
i += seplen;
} else {
i++;
}
}
array->size++;
return array;
}
void array_free(struct array *array) {
if (array->copy == ISCOPY) {
free(array->slot);
}
free(array->vector);
free(array);
}
#define TEST
#ifdef TEST
int main() {
struct array *array;
int i;
array = explode("Hello\r\nWorld\r\nAnd\r\nHello\r\nLiexusong\r\n", "\r\n", ISCOPY);
printf("array size is: %d\n", ArraySize(array));
for (i = 0; i < ArraySize(array); i++) {
printf("array[%d] = %s\n", i, ArrayElem(array, i));
}
array_free(array);
return 0;
}
#endif
|