42_libft/ft_split.c
Camille Chauvet d4bc0e05a5 d
2022-10-04 22:04:23 +02:00

99 lines
2.1 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cchauvet <cchauvet@student.42angoulem +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/09/29 17:37:50 by cchauvet #+# #+# */
/* Updated: 2022/10/04 21:24:29 by cchauvet ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t ft_seglen(const char *s, char c)
{
size_t len;
size_t i;
if (*s == 0)
return (1);
len = 1;
i = 0;
while (s[i])
{
while (s[i] == c && s[i])
i++;
if (s[i])
len++;
while (s[i] != c && s[i])
i++;
}
if (len == 1)
return (2);
return (len);
}
static void *ft_cancel(size_t len, char **tab)
{
size_t i;
i = 0;
while (i < len)
{
free(tab[i]);
i++;
}
free(tab);
return (NULL);
}
static char **ft_segmentator(const char *s, char c, size_t len, char **tab)
{
size_t i;
size_t j;
ssize_t start;
if (tab == NULL)
return (NULL);
i = 0;
j = 0;
while (i < len)
{
while (s[j] == c)
j++;
start = j;
while (s[j] != c)
j++;
tab[i] = ft_substr(s, start, j - start);
if (tab[i] == NULL)
return (ft_cancel(len, tab));
i++;
}
return (tab);
}
char **ft_split(const char *s, char c)
{
char **tab;
size_t len;
if (s == NULL)
return (NULL);
len = ft_seglen(s, c);
tab = malloc(sizeof(char *) * (len));
if (tab == NULL)
return (NULL);
if (c == 0 || !*s)
{
tab[0] = ft_strdup(s);
if (tab[0] == NULL)
return (NULL);
}
else
tab = ft_segmentator(s, c, len - 1, tab);
tab[len - 1] = NULL;
return (tab);
}