Archived
1
0
This repository has been archived on 2024-10-25. You can view files and clone it, but cannot push or open issues or pull requests.
libft/ft_split.c

84 lines
1.9 KiB
C
Raw Normal View History

2023-11-10 18:49:34 +01:00
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: adjoly <adjoly@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
2023-11-12 09:18:34 +01:00
/* Created: 2023/11/12 09:14:19 by adjoly #+# #+# */
/* Updated: 2023/11/12 09:17:04 by adjoly ### ########.fr */
2023-11-10 18:49:34 +01:00
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_countword(char const *s, char sep)
{
int i;
int w_count;
i = 0;
2023-11-11 01:28:12 +01:00
w_count = 0;
2023-11-10 18:49:34 +01:00
while (s[i])
{
2023-11-11 01:28:12 +01:00
if (s[i] != sep && (i == 0 || s[i - 1] == sep))
2023-11-10 18:49:34 +01:00
w_count++;
i++;
}
return (w_count);
}
2023-11-11 11:20:15 +01:00
static int ft_countletter(char const *s, char sep)
2023-11-11 01:28:12 +01:00
{
int i;
i = 0;
2023-11-11 11:20:15 +01:00
while (s[i] != sep && s[i] != '\0')
2023-11-11 01:28:12 +01:00
i++;
return (i);
}
2023-11-11 11:20:15 +01:00
static void *ft_freearr(char **arr)
{
int i;
i = 0;
free(arr[i]);
while (arr[i])
{
i++;
free(arr[i]);
}
free(arr);
return (NULL);
}
2023-11-10 18:49:34 +01:00
char **ft_split(char const *s, char c)
{
int w_count;
char **result;
2023-11-11 11:20:15 +01:00
int i;
int j;
2023-11-10 18:49:34 +01:00
2023-11-12 09:18:34 +01:00
i = -1;
2023-11-11 11:20:15 +01:00
j = 0;
if (s == NULL)
return (NULL);
2023-11-10 18:49:34 +01:00
w_count = ft_countword(s, c);
2023-11-11 01:28:12 +01:00
result = malloc((w_count + 1) * sizeof(char *));
if (result == NULL)
2023-11-11 11:20:15 +01:00
return (ft_freearr(result));
2023-11-12 09:18:34 +01:00
while (++i < w_count)
2023-11-11 01:28:12 +01:00
{
2023-11-11 11:20:15 +01:00
while (s[j] == c)
j++;
if (s[j] != '\0' && s[j] != c)
2023-11-11 01:28:12 +01:00
{
2023-11-11 11:56:43 +01:00
result[i] = ft_substr(s, j, ft_countletter(s + j, c));
j += ft_countletter(s + j, c);
2023-11-11 01:28:12 +01:00
}
}
2023-11-11 11:20:15 +01:00
result[i] = NULL;
2023-11-10 18:49:34 +01:00
return (result);
}