42_libft/ft_split.c

93 lines
2.1 KiB
C
Raw Permalink Normal View History

2022-10-04 08:21:55 -04:00
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cchauvet <cchauvet@student.42angoulem +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
2022-10-05 15:04:45 -04:00
/* Created: 2022/10/05 19:04:34 by cchauvet #+# #+# */
2022-10-28 13:23:50 -04:00
/* Updated: 2022/10/28 19:23:45 by cchauvet ### ########.fr */
2022-10-04 08:21:55 -04:00
/* */
/* ************************************************************************** */
#include "libft.h"
2022-10-05 15:04:45 -04:00
static void *ft_cancel(char **tab, size_t len)
2022-10-04 08:21:55 -04:00
{
size_t i;
2022-10-05 15:04:45 -04:00
if (tab != NULL)
2022-10-04 08:21:55 -04:00
{
2022-10-05 15:04:45 -04:00
i = 0;
while (i < len)
{
free(tab[i]);
2022-10-04 08:21:55 -04:00
i++;
2022-10-05 15:04:45 -04:00
}
free(tab);
2022-10-04 08:21:55 -04:00
}
2022-10-05 15:04:45 -04:00
return (NULL);
2022-10-04 08:21:55 -04:00
}
2022-10-05 15:04:45 -04:00
static size_t ft_seglen(const char *s, char c)
2022-10-04 08:21:55 -04:00
{
2022-10-05 15:04:45 -04:00
size_t len;
2022-10-04 08:21:55 -04:00
2022-10-05 15:04:45 -04:00
if (s == NULL)
return (0);
len = 0;
while (*s != 0)
2022-10-04 08:21:55 -04:00
{
2022-10-05 15:04:45 -04:00
while (*s == c && *s != 0)
s++;
if (*s != 0)
len++;
while (*s != c && *s != 0)
s++;
2022-10-04 08:21:55 -04:00
}
2022-10-05 15:04:45 -04:00
return (len);
2022-10-04 08:21:55 -04:00
}
2022-10-05 15:04:45 -04:00
static char **ft_segsplitter(char **tab, size_t len, const char *s, char c)
2022-10-04 08:21:55 -04:00
{
2022-10-05 15:04:45 -04:00
size_t tab_index;
size_t let_index;
size_t start;
2022-10-04 08:21:55 -04:00
2022-10-05 15:04:45 -04:00
tab_index = 0;
let_index = 0;
start = 0;
if (tab == NULL || s == NULL)
2022-10-04 08:21:55 -04:00
return (NULL);
2022-10-05 15:04:45 -04:00
while (tab_index < len)
2022-10-04 08:21:55 -04:00
{
2022-10-05 15:04:45 -04:00
while (s[let_index] == c && s[let_index] != 0)
let_index++;
start = let_index;
while (s[let_index] != c && s[let_index] != 0)
let_index++;
tab[tab_index] = ft_substr(s, start, let_index - start);
if (tab[tab_index] == NULL)
return (ft_cancel(tab, tab_index));
tab_index++;
2022-10-04 08:21:55 -04:00
}
return (tab);
}
char **ft_split(const char *s, char c)
{
size_t len;
2022-10-05 15:04:45 -04:00
char **tab;
2022-10-04 08:21:55 -04:00
if (s == NULL)
return (NULL);
len = ft_seglen(s, c);
2022-10-05 15:04:45 -04:00
tab = malloc((len + 1) * sizeof(char *));
2022-10-04 08:21:55 -04:00
if (tab == NULL)
return (NULL);
2022-10-05 15:04:45 -04:00
tab[len] = NULL;
if (ft_segsplitter(tab, len, s, c) == NULL)
return (NULL);
2022-10-04 08:21:55 -04:00
return (tab);
}