diff --git a/libft/Makefile b/libft/Makefile index dbd60f87..483003b8 100644 --- a/libft/Makefile +++ b/libft/Makefile @@ -175,6 +175,7 @@ str/ft_strnstr.c\ str/ft_strrchr.c\ str/ft_strreplace.c\ str/ft_strrev.c\ +str/ft_strsplit.c\ str/ft_strstr.c\ str/ft_strsub.c\ str/ft_strtok.c\ diff --git a/libft/src/str/ft_strsplit.c b/libft/src/str/ft_strsplit.c new file mode 100644 index 00000000..a44c4ca1 --- /dev/null +++ b/libft/src/str/ft_strsplit.c @@ -0,0 +1,70 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* ft_strsplit.c :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: jhalford +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2016/11/03 14:58:40 by jhalford #+# #+# */ +/* Updated: 2016/12/05 17:20:45 by jhalford ### ########.fr */ +/* */ +/* ************************************************************************** */ + +#include "libft.h" + +static int ft_countwords(char const *s, char c) +{ + if (c == '\0') + return ((*s == '\0') ? 0 : 1); + while (*s == c) + s++; + if (*s == '\0') + return (0); + while (*s != c && *s != '\0') + s++; + return (1 + ft_countwords(s, c)); +} + +static int get_word_len(char const *str, char c) +{ + int i; + int len; + + i = 0; + len = 0; + while (str[i] == c) + i++; + while (str[i] != c && str[i] != '\0') + { + i++; + len++; + } + return (len); +} + +char **ft_strsplit(char const *s, char c) +{ + int i; + int j; + int k; + char **str2; + + if (!s || !(str2 = (char **)malloc(sizeof(*str2) * + (ft_countwords(s, c) + 1)))) + return (NULL); + i = -1; + j = 0; + while (++i < ft_countwords(s, c)) + { + k = 0; + if (!(str2[i] = ft_strnew(get_word_len(&s[j], c) + 1))) + str2[i] = NULL; + while (s[j] == c) + j++; + while (s[j] != c && s[j]) + str2[i][k++] = s[j++]; + str2[i][k] = '\0'; + } + str2[i] = 0; + return (str2); +}