2022-10-04 08:21:55 -04:00
|
|
|
/* ************************************************************************** */
|
|
|
|
/* */
|
|
|
|
/* ::: :::::::: */
|
|
|
|
/* ft_split.c :+: :+: :+: */
|
|
|
|
/* +:+ +:+ +:+ */
|
|
|
|
/* By: cchauvet <cchauvet@student.42angoulem +#+ +:+ +#+ */
|
|
|
|
/* +#+#+#+#+#+ +#+ */
|
|
|
|
/* Created: 2022/09/29 17:37:50 by cchauvet #+# #+# */
|
2022-10-04 16:04:23 -04:00
|
|
|
/* Updated: 2022/10/04 21:24:29 by cchauvet ### ########.fr */
|
2022-10-04 08:21:55 -04:00
|
|
|
/* */
|
|
|
|
/* ************************************************************************** */
|
|
|
|
|
|
|
|
#include "libft.h"
|
|
|
|
|
|
|
|
static size_t ft_seglen(const char *s, char c)
|
|
|
|
{
|
|
|
|
size_t len;
|
|
|
|
size_t i;
|
|
|
|
|
2022-10-04 16:04:23 -04:00
|
|
|
if (*s == 0)
|
|
|
|
return (1);
|
2022-10-04 08:21:55 -04:00
|
|
|
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++;
|
|
|
|
}
|
2022-10-04 16:04:23 -04:00
|
|
|
if (len == 1)
|
|
|
|
return (2);
|
2022-10-04 08:21:55 -04:00
|
|
|
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++;
|
2022-10-04 16:04:23 -04:00
|
|
|
tab[i] = ft_substr(s, start, j - start);
|
2022-10-04 08:21:55 -04:00
|
|
|
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);
|
2022-10-04 16:04:23 -04:00
|
|
|
tab = malloc(sizeof(char *) * (len));
|
2022-10-04 08:21:55 -04:00
|
|
|
if (tab == NULL)
|
|
|
|
return (NULL);
|
2022-10-04 16:04:23 -04:00
|
|
|
if (c == 0 || !*s)
|
2022-10-04 08:21:55 -04:00
|
|
|
{
|
|
|
|
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);
|
|
|
|
}
|