From c14b4fcdd8f628ac953186517621cc041d2c6c71 Mon Sep 17 00:00:00 2001 From: starnakin Date: Wed, 28 Jun 2023 11:59:28 +0200 Subject: [PATCH] add: split --- src/str/split.c | 54 +++++++++++++++++++++++++++++++++++++++++++++++++ src/str/str.h | 6 ++++++ 2 files changed, 60 insertions(+) create mode 100644 src/str/split.c create mode 100644 src/str/str.h diff --git a/src/str/split.c b/src/str/split.c new file mode 100644 index 0000000..0e44dd0 --- /dev/null +++ b/src/str/split.c @@ -0,0 +1,54 @@ +#include "str.h" + +static void free_tab(char **tab) +{ + for (size_t i = 0; tab[i] != NULL; i++) + free(tab); + free(tab); +} + +static ssize_t fill_tab(const char *str, const char *delimiter, char **tab) +{ + size_t len = 0; + size_t delimiter_len = strlen(delimiter); + const char* tmp = str; + const char* next; + + while (tmp != NULL) + { + while (strcmp(tmp, delimiter) == 0) + tmp += delimiter_len; + next = strstr(tmp, delimiter); + if (tab != NULL) + { + if (next == NULL) + tab[len] = strndup(tmp, strlen(tmp)); + else + tab[len] = strndup(tmp, next - tmp); + if (tab[len] == NULL) + { + free_tab(tab); + return (-1); + } + } + len++; + tmp = next; + } + if (tab != NULL) + tab[len] = NULL; + return (len); +} + +char **split(const char *str, const char *delimiter) +{ + ssize_t len; + char **tab; + + len = fill_tab(str, delimiter, NULL); + tab = malloc((len + 1) * sizeof(char *)); + if (tab == NULL) + return (NULL); + if (fill_tab(str, delimiter, tab) == -1) + return (NULL); + return (tab); +} diff --git a/src/str/str.h b/src/str/str.h new file mode 100644 index 0000000..e89c368 --- /dev/null +++ b/src/str/str.h @@ -0,0 +1,6 @@ +#pragma once +#include +#include +#include + +char **split(const char *str, const char *delimiter);