42-archive/ftp/libft/srcs/str/ft_strsplit.c

70 lines
1.8 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strsplit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jhalford <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/11/03 14:58:40 by jhalford #+# #+# */
/* Updated: 2017/11/10 13:34:15 by jhalford ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_countwords(char const *s, char c)
{
if (c == '\0')
return ((*s == '\0') ? 0 : 1);
while (*s == c)
s++;
if (*s == '\0')
return (0);
while (*s != c && *s != '\0')
s++;
return (1 + ft_countwords(s, c));
}
static int get_word_len(char const *str, char c)
{
int i;
int len;
i = 0;
len = 0;
while (str[i] == c)
i++;
while (str[i] != c && str[i] != '\0')
{
i++;
len++;
}
return (len);
}
char **ft_strsplit(char const *s, char c)
{
int i;
int j;
int k;
char **str2;
if (!s || !(str2 = (char **)ft_malloc(sizeof(*str2) *
(ft_countwords(s, c) + 1))))
return (NULL);
i = -1;
j = 0;
while (++i < ft_countwords(s, c))
{
k = 0;
if (!(str2[i] = ft_strnew(get_word_len(&s[j], c) + 1)))
str2[i] = NULL;
while (s[j] == c)
j++;
while (s[j] != c && s[j])
str2[i][k++] = s[j++];
str2[i][k] = '\0';
}
str2[i] = 0;
return (str2);
}