From a8f7e6e83bc4846c94c0489e0f6e0f807b35073e Mon Sep 17 00:00:00 2001 From: Thomas Vanbesien Date: Sat, 21 Feb 2026 16:29:51 +0100 Subject: Implement libft Part 2 with tests Add ft_substr, ft_strjoin, ft_strtrim, ft_split, ft_itoa, ft_strmapi, ft_striteri, ft_putchar_fd, ft_putstr_fd, ft_putendl_fd, ft_putnbr_fd. --- src/ft_split.c | 67 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 src/ft_split.c (limited to 'src/ft_split.c') diff --git a/src/ft_split.c b/src/ft_split.c new file mode 100644 index 0000000..bb51c85 --- /dev/null +++ b/src/ft_split.c @@ -0,0 +1,67 @@ +#include "libft.h" +#include + +static size_t +_s_count_words (char const *s, char c) +{ + size_t count; + + count = 0; + while (*s) + { + while (*s == c) + s++; + if (*s) + { + count++; + while (*s && *s != c) + s++; + } + } + return (count); +} + +static void +_s_free_all (char **arr, size_t n) +{ + size_t i; + + i = 0; + while (i < n) + free (arr[i++]); + free (arr); +} + +char ** +ft_split (char const *s, char c) +{ + size_t count; + char **arr; + size_t i; + + count = _s_count_words (s, c); + arr = malloc ((count + 1) * sizeof (char *)); + if (!arr) + return (NULL); + i = 0; + while (*s) + { + while (*s == c) + s++; + if (*s) + { + const char *start = s; + while (*s && *s != c) + s++; + arr[i] = ft_substr (start, 0, s - start); + if (!arr[i]) + { + _s_free_all (arr, i); + return (NULL); + } + i++; + } + } + arr[i] = NULL; + return (arr); +} -- cgit v1.2.3