111 lines
2.3 KiB
C
111 lines
2.3 KiB
C
/* ************************************************************************** */
|
|
/* */
|
|
/* ::: :::::::: */
|
|
/* ft_split.c :+: :+: :+: */
|
|
/* +:+ +:+ +:+ */
|
|
/* By: gbaconni <gbaconni@42lausanne.ch> +#+ +:+ +#+ */
|
|
/* +#+#+#+#+#+ +#+ */
|
|
/* Created: 2021/08/22 18:14:04 by gbaconni #+# #+# */
|
|
/* Updated: 2021/08/25 18:26:47 by gbaconni ### ########.fr */
|
|
/* */
|
|
/* ************************************************************************** */
|
|
|
|
#include <stdlib.h>
|
|
#include <stdio.h>
|
|
|
|
int g_t = 0;
|
|
|
|
static char *ft_strncpy(char *dest, char *src, unsigned int n)
|
|
{
|
|
unsigned int i;
|
|
|
|
i = 0;
|
|
while (i < n && src[i] != '\0')
|
|
{
|
|
dest[i] = src[i];
|
|
i++;
|
|
}
|
|
while (i < n)
|
|
{
|
|
dest[i] = '\0';
|
|
i++;
|
|
}
|
|
dest[i] = '\0';
|
|
return (dest);
|
|
}
|
|
|
|
static int ft_is_charset(char c, char *charset)
|
|
{
|
|
int i;
|
|
|
|
i = 0;
|
|
while (charset[i] != '\0')
|
|
{
|
|
if (c == charset[i])
|
|
return (1);
|
|
i++;
|
|
}
|
|
return (0);
|
|
}
|
|
|
|
static int ft_split_len(char *str, char *charset)
|
|
{
|
|
char *p_str;
|
|
int size;
|
|
|
|
size = 2;
|
|
if (str == NULL || charset == NULL)
|
|
return (size);
|
|
p_str = str;
|
|
while (*p_str != '\0')
|
|
{
|
|
if (ft_is_charset(*p_str++, charset) == 1)
|
|
size++;
|
|
}
|
|
return (size);
|
|
}
|
|
|
|
char *ft_copy(char *str, int size)
|
|
{
|
|
char *result;
|
|
|
|
result = NULL;
|
|
if (size > 0)
|
|
{
|
|
result = (char *) malloc((size + 1) * sizeof(char));
|
|
if (!result)
|
|
return (NULL);
|
|
ft_strncpy(result, str, size);
|
|
}
|
|
return (result);
|
|
}
|
|
|
|
char **ft_split(char *str, char *charset)
|
|
{
|
|
char **strs;
|
|
char *start;
|
|
int i;
|
|
|
|
strs = malloc(ft_split_len(str, charset) * sizeof(strs));
|
|
if (strs == NULL || charset == NULL || str == NULL)
|
|
return (NULL);
|
|
start = str;
|
|
i = 0;
|
|
while (1)
|
|
{
|
|
if (ft_is_charset(*str, charset) == 1 || (*str == '\0' && g_t > 0))
|
|
{
|
|
if (str - start > 0)
|
|
strs[i++] = ft_copy(start, str - start);
|
|
start = str + 1;
|
|
}
|
|
else
|
|
g_t++;
|
|
if (*str == '\0')
|
|
break ;
|
|
str++;
|
|
}
|
|
strs[i] = ft_copy(str, 0);
|
|
return (strs);
|
|
}
|