/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_split.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: erey-bet +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2022/07/28 09:52:05 by erey-bet #+# #+# */ /* Updated: 2023/01/17 15:40:25 by erey-bet ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static int get_len_all(char const *s, char c) { int i; int check; int count; i = 0; check = 0; count = 0; while (s[i]) { if (s[i] != c && check == 0) { count++; check = 1; } else if (s[i] == c && check == 1) check = 0; i++; } return (count); } static int get_len_next(char const *s, char c, int i) { int y; int count; y = i; count = 0; while (s[y] == c) y++; while (s[y] && s[y++] != c) count++; return (count); } static void *ft_malloc_split(char **strs, int *iyx, char const *s, char c) { iyx[1]++; strs[iyx[1]] = malloc(get_len_next(s, c, iyx[0]) + 1); if (strs[iyx[1]] == NULL) { iyx[1]--; while (iyx[1] >= 0) { free(strs[iyx[1]]); iyx[1]--; } free(strs); return (NULL); } return (""); } static char **ft_split_bis(char const *s, char c, char **strs, int *iyx) { int boo; boo = 0; while (s[iyx[0]]) { if (s[iyx[0]] != c) { if (boo == 0) if (ft_malloc_split(strs, iyx, s, c) == NULL) return (NULL); boo = 1; strs[iyx[1]][iyx[2]] = s[iyx[0]]; iyx[2]++; } else if (boo == 1) { strs[iyx[1]][iyx[2]] = '\0'; iyx[2] = 0; boo = 0; } iyx[0]++; } if (boo == 1) strs[iyx[1]][iyx[2]] = '\0'; return (strs); } char **ft_split(char const *s, char c) { char **strs; int iyx[3]; iyx[0] = 0; iyx[1] = -1; iyx[2] = 0; if (s == NULL) return (NULL); strs = malloc(sizeof(char *) * (get_len_all(s, c) + 2)); if (strs == NULL) return (NULL); if (ft_split_bis(s, c, strs, iyx) == NULL) return (NULL); iyx[1]++; strs[iyx[1]] = NULL; return (strs); }