Files
42_INT_01_libft/srcs/ft_split.c

124 lines
2.6 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: hulamy <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/11/25 14:00:13 by hulamy #+# #+# */
/* Updated: 2019/11/27 21:35:21 by hulamy ### ########.fr */
/* */
/* ************************************************************************** */
/*
** return an array of string with each word found in str, with c as separator
*/
/*
** #include <libc.h>
**
** size_t ft_strlen(const char *str)
** {
** size_t i;
**
** i = 0;
** while (str[i])
** i++;
** return (i);
** }
**
** char *ft_substr(char const *s, unsigned int start, size_t len)
** {
** char *str;
** size_t i;
**
** if (!s)
** return (NULL);
** if (ft_strlen(s) < start)
** return ("");
** if (!(str = (char *)malloc(sizeof(char) * (len + 1))))
** return (NULL);
** i = 0;
** while (i < len && s[start])
** str[i++] = s[start++];
** str[i] = '\0';
** return (str);
** }
**
** char **ft_split(char const *s, char c);
**
** int main(int ac, char **av)
** //int main(void)
** {
** char **str;
** int i;
**
** char *s;
** char c;
**
** if (ac == 3)
** {
** i = 0;
** s = av[1];
** // s = "lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed non risus. Suspendisse";
** c = av[2][0];
** // c = ' ';
** str = ft_split(s, c);
** while (str[i])
** printf("%s\n", str[i++]);
** }
** return (0);
** }
*/
#include "libft.h"
static int ft_count_word(char const *s, char c)
{
int i;
int words;
i = 0;
words = 0;
while (s[i])
{
if (s[i] != c)
{
words++;
while (s[i] && s[i] != c)
i++;
}
else
i++;
}
return (words);
}
char **ft_split(char const *s, char c)
{
char **array;
int i;
int j;
int len;
i = -1;
j = 0;
if (!s || !c)
return (NULL);
if (!(array = (char **)malloc(sizeof(char *) * (ft_count_word(s, c) + 1))))
return (NULL);
while (s[++i])
{
if (s[i] != c)
{
len = 0;
while (s[i + len] && s[i + len] != c)
len++;
array[j++] = ft_substr(s, i, len);
i = i + len - 1;
}
}
array[j] = 0;
return (array);
}