libft/ft_split.c
2024-10-17 17:02:35 +02:00

112 lines
2.4 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kcolin <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/10/17 16:09:01 by kcolin #+# #+# */
/* Updated: 2024/10/17 16:50:01 by kcolin ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#include <stdlib.h>
static size_t count_segments(char const *s, char c)
{
size_t i;
int count;
i = 0;
count = 0;
while (s[i] != '\0')
{
if (s[i] != c && (s[i + 1] == c || s[i + 1] == '\0'))
count++;
i++;
}
return (count);
}
static char *ft_strnchr(const char *s, int c)
{
int i;
i = 0;
while (s[i] != '\0')
{
if (s[i] != c)
return ((char *)s + i);
i++;
}
return (0);
}
static void free_buf(char **buf, size_t length)
{
size_t i;
i = 0;
while (i < length)
{
free(buf[i]);
i++;
}
free(buf);
}
char **ft_split(char const *s, char c)
{
char **out;
size_t s_idx;
size_t out_idx;
size_t length;
out = ft_calloc(count_segments(s, c) + 1, sizeof(char *));
if (out == NULL)
return (NULL);
s_idx = 0;
out_idx = 0;
while (out_idx < count_segments(s, c))
{
s_idx = ft_strnchr(s + s_idx, c) - s;
length = ft_strchr(s + s_idx, c) - s - s_idx;
out[out_idx] = ft_substr(s, s_idx, length);
if (out[out_idx] == NULL)
{
free_buf(out, out_idx);
return (NULL);
}
s_idx += length;
out_idx++;
}
return (out);
}
/*
#include <stdio.h> // TODO: BAD
int main(int argc, char **argv)
{
if (argc == 3)
{
int count = count_segments(argv[1], argv[2][0]);
printf("segments: %d\n", count);
char **buf = ft_split(argv[1], argv[2][0]);
size_t i = 0;
while (buf[i] != NULL)
{
printf("%zu\t'%s'\n", i, buf[i]);
i++;
}
free_buf(buf, i);
return (0);
}
else
{
printf("Usage: %s <string> <separator>\n", argv[0]);
return (1);
}
}
*/