summaryrefslogtreecommitdiff
path: root/ft_split.c
diff options
context:
space:
mode:
authorDominik Kaiser2024-03-10 13:35:18 +0100
committerDominik Kaiser2024-03-10 13:35:18 +0100
commit3c90d29fe5bf9ba6da090cd59c8c139d269f8bd4 (patch)
tree4e2ac5e37895152cf1497ea7e5dc084bd510a1e6 /ft_split.c
parentc63ee0defff25db4612e9114d847b5045948e366 (diff)
downloadlibft-3c90d29fe5bf9ba6da090cd59c8c139d269f8bd4.tar.gz
libft-3c90d29fe5bf9ba6da090cd59c8c139d269f8bd4.zip
Add everything
Diffstat (limited to 'ft_split.c')
-rw-r--r--ft_split.c104
1 files changed, 104 insertions, 0 deletions
diff --git a/ft_split.c b/ft_split.c
new file mode 100644
index 0000000..e9ba9f9
--- /dev/null
+++ b/ft_split.c
@@ -0,0 +1,104 @@
+/* ************************************************************************** */
+/* */
+/* ::: :::::::: */
+/* ft_split.c :+: :+: :+: */
+/* +:+ +:+ +:+ */
+/* By: dkaiser <dkaiser@student.42heilbronn.de +#+ +:+ +#+ */
+/* +#+#+#+#+#+ +#+ */
+/* Created: 2024/03/08 15:36:44 by dkaiser #+# #+# */
+/* Updated: 2024/03/10 13:09:06 by dkaiser ### ########.fr */
+/* */
+/* ************************************************************************** */
+
+#include "libft.h"
+
+static int get_word_count(char const *s, char c)
+{
+ int word_count;
+ int cur_len;
+
+ word_count = 0;
+ cur_len = 0;
+ while (*s)
+ {
+ if (!(*s) || *s == c)
+ {
+ cur_len = 0;
+ }
+ else
+ {
+ if (!cur_len)
+ word_count++;
+ cur_len++;
+ }
+ s++;
+ }
+ return (word_count);
+}
+
+static char *get_next_token(char const **ptr_s, char c)
+{
+ int i;
+ int len;
+ char const *s;
+ char *result;
+
+ s = *ptr_s;
+ while (*s && *s == c)
+ s++;
+ if (!*s)
+ return (0);
+ len = 0;
+ while (s[len] && s[len] != c)
+ len++;
+ result = malloc(sizeof(char) * (len + 1));
+ if (!result)
+ return (0);
+ i = 0;
+ while (i < len)
+ result[i++] = *(s++);
+ result[i] = '\0';
+ *ptr_s = s;
+ return (result);
+}
+
+char **ft_split(char const *s, char c)
+{
+ char **result;
+ int word_count;
+ int w;
+
+ word_count = get_word_count((char *)s, c);
+ result = malloc(sizeof(char *) * (word_count + 1));
+ if (!result)
+ return (0);
+ w = 0;
+ while (w < word_count)
+ {
+ result[w] = get_next_token(&s, c);
+ if (!result[w])
+ {
+ while (w--)
+ free(result[w]);
+ free(result);
+ return (0);
+ }
+ w++;
+ }
+ result[w] = 0;
+ return (result);
+}
+
+/* #include <stdio.h> */
+/* int main() */
+/* { */
+/* char s[] = " split this for me !"; */
+/* char **split = ft_split(s, ' '); */
+
+/* if (split) { */
+/* while(*split) { */
+/* printf("%s\n", *split); */
+/* split++; */
+/* } */
+/* } */
+/* } */