115 lines
2.5 KiB
C
115 lines
2.5 KiB
C
/* ************************************************************************** */
|
|
/* */
|
|
/* ::: :::::::: */
|
|
/* ft_split.c :+: :+: :+: */
|
|
/* +:+ +:+ +:+ */
|
|
/* By: cchauvet <cchauvet@student.42angoulem +#+ +:+ +#+ */
|
|
/* +#+#+#+#+#+ +#+ */
|
|
/* Created: 2022/10/05 19:04:34 by cchauvet #+# #+# */
|
|
/* Updated: 2022/12/06 17:28:21 by cchauvet ### ########.fr */
|
|
/* */
|
|
/* ************************************************************************** */
|
|
|
|
#include "pushswap.h"
|
|
|
|
static void *ft_cancel(char **tab, size_t len)
|
|
{
|
|
size_t i;
|
|
|
|
if (tab != NULL)
|
|
{
|
|
i = 0;
|
|
while (i < len)
|
|
{
|
|
free(tab[i]);
|
|
i++;
|
|
}
|
|
free(tab);
|
|
}
|
|
return (NULL);
|
|
}
|
|
|
|
char *ft_substr(char const *s, unsigned int start, size_t len)
|
|
{
|
|
ssize_t size;
|
|
char *ptr;
|
|
|
|
if (s == NULL)
|
|
return (NULL);
|
|
size = ft_strlen(s);
|
|
size -= start;
|
|
if (size < 0)
|
|
size = 0;
|
|
if ((size_t)size > len)
|
|
size = len;
|
|
ptr = malloc((size + 1) * sizeof(char));
|
|
if (ptr == NULL)
|
|
return (NULL);
|
|
ptr[size] = '\0';
|
|
while (size-- > 0)
|
|
ptr[size] = s[start + size];
|
|
return (ptr);
|
|
}
|
|
|
|
size_t ft_seglen(const char *s, char c)
|
|
{
|
|
size_t len;
|
|
|
|
if (s == NULL)
|
|
return (0);
|
|
len = 0;
|
|
while (*s != 0)
|
|
{
|
|
while (*s == c && *s != 0)
|
|
s++;
|
|
if (*s != 0)
|
|
len++;
|
|
while (*s != c && *s != 0)
|
|
s++;
|
|
}
|
|
return (len);
|
|
}
|
|
|
|
static char **ft_segsplitter(char **tab, size_t len, const char *s, char c)
|
|
{
|
|
size_t tab_index;
|
|
size_t let_index;
|
|
size_t start;
|
|
|
|
tab_index = 0;
|
|
let_index = 0;
|
|
start = 0;
|
|
if (tab == NULL || s == NULL)
|
|
return (NULL);
|
|
while (tab_index < len)
|
|
{
|
|
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++;
|
|
}
|
|
return (tab);
|
|
}
|
|
|
|
char **ft_split(const char *s, char c)
|
|
{
|
|
size_t len;
|
|
char **tab;
|
|
|
|
if (s == NULL)
|
|
return (NULL);
|
|
len = ft_seglen(s, c);
|
|
tab = malloc((len + 1) * sizeof(char *));
|
|
if (tab == NULL)
|
|
return (NULL);
|
|
tab[len] = NULL;
|
|
if (ft_segsplitter(tab, len, s, c) == NULL)
|
|
return (NULL);
|
|
return (tab);
|
|
}
|