60 lines
1.5 KiB
C
60 lines
1.5 KiB
C
/* ************************************************************************** */
|
|
/* */
|
|
/* ::: o_ :::::: ::: */
|
|
/* ft_split.c :+: / :+::+: :+: */
|
|
/* +:+ > +:++:+ +:+ */
|
|
/* By: whaffman <whaffman@student.codam.nl> +#+ +:+ +#++#++:++#++ */
|
|
/* +#+ +#+#+ +#++#+ +#+ \o/ */
|
|
/* Created: 2024/10/10 17:00:26 by whaffman #+#+# #+#+# #+# #+# | */
|
|
/* Updated: 2024/10/10 17:00:26 by whaffman ### ### ### ### / \ */
|
|
/* */
|
|
/* ************************************************************************** */
|
|
|
|
#include <stdlib.h>
|
|
#include "libft.h"
|
|
|
|
static int count_words(char const *s, char c)
|
|
{
|
|
int n;
|
|
int i;
|
|
|
|
n = 0;
|
|
i = 0;
|
|
while (s[i])
|
|
{
|
|
if (s[i] != c && (s[i + 1] == c || s[i + 1] == '\0'))
|
|
n++;
|
|
i++;
|
|
}
|
|
return (n);
|
|
}
|
|
|
|
char **ft_split(char const *s, char c)
|
|
{
|
|
char **result;
|
|
int n;
|
|
int i;
|
|
int j;
|
|
|
|
if (!s)
|
|
return (NULL);
|
|
result = malloc((count_words(s, c) + 1) * sizeof(char *));
|
|
if (!result)
|
|
return (NULL);
|
|
i = 0;
|
|
n = 0;
|
|
while (s[i])
|
|
{
|
|
j = 0;
|
|
while (s[i] == c)
|
|
i++;
|
|
while (s[i + j] && s[i + j] != c)
|
|
j++;
|
|
if (j)
|
|
result[n++] = ft_substr(s, i, j);
|
|
i += j;
|
|
}
|
|
result[n] = NULL;
|
|
return (result);
|
|
}
|