aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorAlessandro Iezzi <aiezzi@alessandroiezzi.it>2023-05-11 17:26:36 +0200
committerAlessandro Iezzi <aiezzi@alessandroiezzi.it>2023-05-11 17:26:36 +0200
commita7c32eec5fd2cb5523d567912e6aec539e793c0f (patch)
tree33af2aa60a65882e581bfb2eb1af4e0d508e80df /src
parentd37eb3feb226623431a464b189edf2fc2f31beed (diff)
downloadstring2-a7c32eec5fd2cb5523d567912e6aec539e793c0f.tar.gz
string2-a7c32eec5fd2cb5523d567912e6aec539e793c0f.zip
Add the strsplit() function
Diffstat (limited to 'src')
-rw-r--r--src/string2.c33
-rw-r--r--src/string2.h2
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