/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_split.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: hulamy +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2022/05/04 18:15:10 by hulamy #+# #+# */ /* Updated: 2022/05/04 18:35:56 by hulamy ### ########.fr */ /* */ /* ************************************************************************** */ /* ** return an array of string with each word found in str, with c as separator */ /* ** #include ** #include ** #include ** ** size_t ft_strlen(const char *str) ** { ** size_t i; ** ** i = 0; ** while (str[i]) ** i++; ** return (i); ** } ** ** char *ft_substr(char const *s, unsigned int start, size_t len) ** { ** char *str; ** size_t i; ** ** if (!s) ** return (NULL); ** if (ft_strlen(s) < start) ** return (""); ** if (!(str = (char *)malloc(sizeof(char) * (len + 1)))) ** return (NULL); ** i = 0; ** while (i < len && s[start]) ** str[i++] = s[start++]; ** str[i] = '\0'; ** return (str); ** } ** ** char **ft_split(char const *s, char c); ** char **ft_strsplit(char const *s, char c); ** ** int main(void) ** { ** char **str; ** int i; ** ** char *s; ** char c; ** ** i = -1; ** // s = NULL; ** s = "hello les amis :)"; ** c = ' '; ** str = ft_split(s, c); ** printf("s : '%s'\n", s); ** printf("*str : '%p'\n", str[0]); ** while (str[++i]) ** printf("str[%i] : '%s'\n", i, str[i]); ** while (str[--i]) ** free(str[i]); ** free(str); ** return (0); ** } */ #include "libft.h" static int count(char const *s, char c) { int i; int words; i = -1; words = 0; while (s[++i] != '\0') if (s[i] != c && ++words) while (s[i + 1] != '\0' && s[i + 1] != c) i++; return (words); } void *free_array(char **array, int w) { int i; i = 0; while (array[i] != NULL && i < w) free(array[i++]); free(array); return (NULL); } char **empty_s(char **empty) { empty = (char **)malloc(sizeof(char *) * 1); if (!empty) return (NULL); empty[0] = NULL; return (empty); } static int copy_portion(char **array, char const *s, int len) { *array = ft_substr(s, 0, len); if (!(*array)) return (0); return (1); } char **ft_split(char const *s, char c) { char **array; int w; int len; if (!s) return (empty_s(NULL)); array = (char **)malloc(sizeof(char *) * (count(s, c) + 1)); if (!array) return (NULL); w = 0; while (*s != '\0') { len = 0; if (*s != c) { while (s[len] != '\0' && s[len] != c) len++; if (!copy_portion(&array[w++], s, len)) return (free_array(array, w)); s += len - 1; } s++; } array[w] = NULL; return (array); }