diff --git a/libft/src/str/ft_strsplit.c b/libft/src/str/ft_strsplit.c index d5d3496b..b1aa03a2 100644 --- a/libft/src/str/ft_strsplit.c +++ b/libft/src/str/ft_strsplit.c @@ -6,100 +6,48 @@ /* By: jhalford +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/11/03 14:58:40 by jhalford #+# #+# */ -/* Updated: 2016/11/03 15:00:19 by jhalford ### ########.fr */ +/* Updated: 2016/11/05 17:58:23 by jhalford ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" -static char **alloc_table(char **table, const char *str, char c) +static int countwords(char const *s, char c) { - int i; - int n_words; - - i = 0; - n_words = 0; - while (str[i] == c) - i++; - while (str[i] != '\0') - { - i++; - if (str[i] == c) - { - n_words++; - while (str[i] == c) - i++; - } - } - if (str[i - 1] != c) - n_words++; - table = (char**)malloc(sizeof(*table) * (n_words + 10)); - table[n_words] = 0; - return (table); -} - -static char **alloc_words(char **table, const char *str, char c) -{ - int i; - int j; - int k; - - i = 0; - j = 0; - k = 0; - while (str[i] == c) - i++; - while (str[i] != '\0') - { - i++; - if (str[i] == c || !str[i]) - { - table[j] = (char*)malloc(sizeof(**table) * (k + 10)); - j++; - k = 0; - while (str[i] == c) - i++; - } - k++; - } - return (table); -} - -static char **fill_table(char **table, const char *str, char c) -{ - int i; - int j; - int k; - - i = 0; - j = 0; - k = 0; - while (str[i] == c) - i++; - while (str[i] != '\0') - { - table[j][k] = str[i]; - i++; - k++; - if (str[i] == c || !str[i]) - { - table[j][k] = '\0'; - j++; - k = 0; - while (str[i] == c) - i++; - } - } - return (table); + 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 + countwords(s, c)); } char **ft_strsplit(char const *s, char c) { - char **table; + char **arr; + int i; + int j; + int w; - table = 0; - table = alloc_table(table, s, c); - table = alloc_words(table, s, c); - table = fill_table(table, s, c); - return (table); + w = countwords(s, c); + if ((arr = (char **)malloc((w + 1) * sizeof(char *)))) + { + i = 0; + while (i < w) + { + while (*s == c) + ++s; + j = 0; + while (*(s + j) != c) + ++j; + if ((arr[i] = ft_strnew(j))) + ft_strncpy(arr[i++], s, j); + s += j; + } + arr[i] = 0; + } + return (arr); }