42_push_swap/ft_split.c

117 lines
2.5 KiB
C
Raw Normal View History

2022-11-30 14:11:35 -05:00
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cchauvet <cchauvet@student.42angoulem +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/10/05 19:04:34 by cchauvet #+# #+# */
2022-12-11 09:49:45 -05:00
/* Updated: 2022/12/11 15:10:47 by cchauvet ### ########.fr */
2022-11-30 14:11:35 -05:00
/* */
/* ************************************************************************** */
2022-12-06 11:35:45 -05:00
#include "pushswap.h"
2022-11-30 14:11:35 -05:00
2022-12-11 09:49:45 -05:00
void ft_cancel(char **tab, size_t len)
2022-11-30 14:11:35 -05:00
{
size_t i;
if (tab != NULL)
{
i = 0;
while (i < len)
{
free(tab[i]);
i++;
}
free(tab);
}
}
2022-12-06 11:35:45 -05:00
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)
2022-11-30 14:11:35 -05:00
{
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)
2022-12-11 09:49:45 -05:00
{
ft_cancel(tab, tab_index);
return (NULL);
}
2022-11-30 14:11:35 -05:00
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);
}