diff options
author | 2023-05-11 17:26:36 +0200 | |
---|---|---|
committer | 2023-05-11 17:26:36 +0200 | |
commit | a7c32eec5fd2cb5523d567912e6aec539e793c0f (patch) | |
tree | 33af2aa60a65882e581bfb2eb1af4e0d508e80df | |
parent | d37eb3feb226623431a464b189edf2fc2f31beed (diff) | |
download | string2-a7c32eec5fd2cb5523d567912e6aec539e793c0f.tar.gz string2-a7c32eec5fd2cb5523d567912e6aec539e793c0f.zip |
Add the strsplit() function
-rw-r--r-- | src/string2.c | 33 | ||||
-rw-r--r-- | src/string2.h | 2 |
2 files changed, 35 insertions, 0 deletions
diff --git a/src/string2.c b/src/string2.c new file mode 100644 index 0000000..2d59897 --- /dev/null +++ b/src/string2.c @@ -0,0 +1,33 @@ +/* See LICENSE file for copyright and license details. */ + +#include <stdlib.h> +#include <string.h> + +char ** +strsplit(char *str, char delim, int *size) +{ + char **lines = NULL; + char *s = str; + + int count = 0; + + for (int start = 0, end = 0; ; s++, end++) { + if (*s == delim || *s == '\0') { + int _size = end - start; + lines = realloc(lines, sizeof(char *) * ++count); + int idx = count - 1; + if (_size > 1) { + lines[idx] = calloc(_size + 1, sizeof(char *)); + strncpy(lines[idx], str + start, _size); + } else { + lines[idx] = strdup(""); + } + start = end + 1; /* plus 1 - skip the delim */ + } + if (*s == '\0') break; + } + + *size = count; + + return lines; +} diff --git a/src/string2.h b/src/string2.h index 228cc8e..0ffa2b3 100644 --- a/src/string2.h +++ b/src/string2.h @@ -5,6 +5,8 @@ #include <string.h> +char **strsplit(char *str, char delim, int *size); + #define strstarts(str, prefix) (strncmp(str, prefix, strlen(prefix)) == 0) static int |