libft/ft_split.c
2023-12-12 17:30:46 +01:00

76 lines
1.8 KiB
C
Executable File

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: fgras-ca <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/02/17 13:12:04 by fgras-ca #+# #+# */
/* Updated: 2023/02/21 11:04:10 by fgras-ca ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int count_words(const char *s, char c)
{
int count;
int trigger;
count = 0;
trigger = 0;
while (*s)
{
if (*s != c && trigger == 0)
{
trigger = 1;
count++;
}
else if (*s == c)
trigger = 0;
s++;
}
return (count);
}
static char *word_cpy(const char *s, int start, int end)
{
char *word;
int i;
i = 0;
word = malloc(sizeof(char) * (end - start + 1));
while (start < end)
word[i++] = s[start++];
word[i] = '\0';
return (word);
}
char **ft_split(char const *s, char c)
{
size_t i;
size_t j;
int index;
char **split;
split = malloc(sizeof(char *) * (count_words(s, c) + 1));
if (!s || !split)
return (0);
i = 0;
j = 0;
index = -1;
while (i <= ft_strlen(s))
{
if (s[i] != c && index < 0)
index = i;
else if ((s[i] == c || i == ft_strlen(s)) && index >= 0)
{
split[j++] = word_cpy(s, index, i);
index = -1;
}
i++;
}
split[j] = 0;
return (split);
}