60 lines
1.5 KiB
C
60 lines
1.5 KiB
C
/* ************************************************************************** */
|
|
/* */
|
|
/* ::: :::::::: */
|
|
/* ft_split.c :+: :+: :+: */
|
|
/* +:+ +:+ +:+ */
|
|
/* By: whaffman <whaffman@student.codam.nl> +#+ +:+ +#+ */
|
|
/* +#+#+#+#+#+ +#+ */
|
|
/* Created: 2024/07/05 18:42:09 by whaffman #+# #+# */
|
|
/* Updated: 2024/07/10 14:10:57 by whaffman ### ########.fr */
|
|
/* */
|
|
/* ************************************************************************** */
|
|
|
|
#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);
|
|
}
|