97 lines
2.1 KiB
C
97 lines
2.1 KiB
C
/* ************************************************************************** */
|
|
/* */
|
|
/* ::: :::::::: */
|
|
/* ft_split.c :+: :+: :+: */
|
|
/* +:+ +:+ +:+ */
|
|
/* By: pbonilla <eirodeis.lepnj@gmail.com> +#+ +:+ +#+ */
|
|
/* +#+#+#+#+#+ +#+ */
|
|
/* Created: 2021/02/01 08:32:47 by pbonilla #+# #+# */
|
|
/* Updated: 2021/02/07 14:09:27 by pbonilla ### ########.fr */
|
|
/* */
|
|
/* ************************************************************************** */
|
|
|
|
#include "libft.h"
|
|
|
|
int count_word(char const *s, char c)
|
|
{
|
|
int i;
|
|
int nb_word;
|
|
|
|
i = -1;
|
|
nb_word = 0;
|
|
while (s[++i])
|
|
{
|
|
if (s[i] == c && i != 0 && s[i - 1] != c)
|
|
++nb_word;
|
|
}
|
|
if (i == 0 || s[i - 1] != c)
|
|
++nb_word;
|
|
return (nb_word);
|
|
}
|
|
|
|
int count_char(char const *s, char c, int i)
|
|
{
|
|
int size;
|
|
|
|
size = 0;
|
|
while (s[i] && s[i] != c)
|
|
{
|
|
++size;
|
|
++i;
|
|
}
|
|
return (size);
|
|
}
|
|
|
|
char **free_all(char **splitey, int n)
|
|
{
|
|
while (n > 0)
|
|
{
|
|
--n;
|
|
free(splitey[n]);
|
|
}
|
|
free(splitey);
|
|
return (NULL);
|
|
}
|
|
|
|
char **fill_splitey(char const *s, char **splitey, char c, int nb)
|
|
{
|
|
int i;
|
|
int j;
|
|
int k;
|
|
|
|
i = 0;
|
|
j = 0;
|
|
while (s[i] && j < nb)
|
|
{
|
|
k = 0;
|
|
while (s[i] == c)
|
|
++i;
|
|
if (!(splitey[j] = malloc(sizeof(char) * (count_char(s, c, i) + 1))))
|
|
return (free_all(splitey, j));
|
|
while (s[i] && s[i] != c)
|
|
splitey[j][k++] = s[i++];
|
|
splitey[j][k] = 0;
|
|
++j;
|
|
}
|
|
splitey[j] = 0;
|
|
return (splitey);
|
|
}
|
|
|
|
char **ft_split(char const *s, char c)
|
|
{
|
|
char **splitey;
|
|
int nb_words;
|
|
|
|
if (!s)
|
|
return (NULL);
|
|
nb_words = count_word(s, c);
|
|
if (!(splitey = malloc(sizeof(char *) * (nb_words + 1))))
|
|
return (NULL);
|
|
if (!nb_words)
|
|
{
|
|
splitey[0] = 0;
|
|
return (splitey);
|
|
}
|
|
return (fill_splitey(s, splitey, c, nb_words));
|
|
}
|