97 lines
2.0 KiB
C
97 lines
2.0 KiB
C
/* ************************************************************************** */
|
|
/* */
|
|
/* ::: :::::::: */
|
|
/* ft_split.c :+: :+: :+: */
|
|
/* +:+ +:+ +:+ */
|
|
/* By: cchauvet <cchauvet@student.42angoulem +#+ +:+ +#+ */
|
|
/* +#+#+#+#+#+ +#+ */
|
|
/* Created: 2022/09/29 17:37:50 by cchauvet #+# #+# */
|
|
/* Updated: 2022/10/04 13:53:25 by cchauvet ### ########.fr */
|
|
/* */
|
|
/* ************************************************************************** */
|
|
|
|
#include "libft.h"
|
|
|
|
static size_t ft_seglen(const char *s, char c)
|
|
{
|
|
size_t len;
|
|
size_t i;
|
|
|
|
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++;
|
|
}
|
|
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_strndup(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)
|
|
{
|
|
tab[0] = ft_strdup(s);
|
|
if (tab[0] == NULL)
|
|
return (NULL);
|
|
}
|
|
else
|
|
tab = ft_segmentator(s, c, len - 1, tab);
|
|
if (tab == NULL)
|
|
return (NULL);
|
|
tab[len - 1] = NULL;
|
|
return (tab);
|
|
}
|