42_cub3d/Libft/ft_split.c
2024-10-09 03:35:09 +02:00

78 lines
1.8 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: grobledo <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/02/21 11:11:19 by grobledo #+# #+# */
/* Updated: 2023/02/21 18:03:11 by grobledo ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
int ft_countword(const char *s, char c)
{
int i;
int j;
i = 0;
j = 0;
while (s[i])
{
while (s[i] == c)
i++;
if (s[i] != '\0')
j++;
while (s[i] != c && s[i])
i++;
}
return (j);
}
char *ft_strdup_modif(const char *s, char c, size_t i)
{
size_t k;
char *dest;
k = 0;
while (s[i + k] && s[i + k] != c)
k++;
dest = ft_calloc(sizeof(char), (k + 1));
k = 0;
if (dest == 0)
return (NULL);
while (s[i + k] && s[i + k] != c)
{
dest[k] = s[i + k];
k++;
}
return (dest);
}
char **ft_split(const char *s, char c)
{
size_t i;
size_t j;
char **res;
if (!s)
return (NULL);
res = ft_calloc(sizeof (char *), (ft_countword(s, c) + 1));
if (!res)
return (NULL);
i = 0;
j = 0;
while (s[i])
{
while (s[i] == c)
i++;
if (s[i] == '\0')
break ;
res[j] = ft_strdup_modif(s, c, i);
j++;
while (s[i] != c && s[i])
i++;
}
return (res);
}