Projet de l'école 42 : Libft
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

103 lines
2.7 KiB

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: narnaud <narnaud@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/10/20 15:43:48 by narnaud #+# #+# */
/* Updated: 2022/03/24 09:22:49 by narnaud ### ########.fr */
/* */
/* ************************************************************************** */
#include "../libft.h"
static int ft_strlen_to(char const *str, int i, char ch, int lf_not)
{
if (!str[i])
return (i);
if ((!lf_not && str[i] == ch) || (lf_not && !(str[i] == ch)))
return (i);
return (ft_strlen_to(str, ++i, ch, lf_not));
}
static int goto_cur_word(char const *str, char ch, int *words_len, int j_word)
{
int i_word;
int i;
i_word = 0;
i = 0;
i += ft_strlen_to(str, i, ch, 1) - i;
while (i_word < j_word)
{
i += words_len[i_word++];
i += ft_strlen_to(str, i, ch, 1) - i;
}
return (i);
}
static char *ft_get_word(char const *str, char ch, int *words_len, int j_word)
{
int i;
int j;
char *output;
output = ft_calloc((words_len[j_word] + 1), sizeof(char));
if (output == NULL)
return (output);
i = goto_cur_word(str, ch, words_len, j_word);
j = 0;
while (j < words_len[j_word])
{
i += ft_strlen_to(str, i, ch, 1) - i;
output[j] = str[i + j];
j++;
}
output[j] = '\0';
return (output);
}
int get_words_len(int **words_len, char const *str, char ch)
{
int i;
int strlen;
int words_count;
i = 0;
words_count = 0;
strlen = ft_strlen_to(str, 0, '\0', 0);
while (i < strlen)
{
(*words_len)[words_count] = ft_strlen_to(str, i, ch, 0) - i;
i += (*words_len)[words_count] + 1;
if ((*words_len)[words_count] && ++words_count)
(*words_len)[words_count] = 0;
}
return (words_count);
}
char **ft_split(char const *str, char ch)
{
int i;
int words_count;
int *words_len;
char **output;
if (!str)
return (NULL);
i = -1;
words_len = ft_calloc(200, sizeof(int));
if (!words_len)
return (NULL);
words_count = get_words_len(&words_len, str, ch);
output = ft_calloc(words_count + 1, sizeof(char *));
if (!output)
return (NULL);
i = -1;
while (++i < words_count)
output[i] = ft_get_word(str, ch, words_len, i);
output[i] = NULL;
free(words_len);
return (output);
}