piscine/c07/ex05/ft_split.c
Willem Haffmans 607ce08c18 all
2024-09-10 00:18:01 +02:00

127 lines
2.6 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: whaffman <whaffman@student.codam.nl> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/06/18 10:44:32 by whaffman #+# #+# */
/* Updated: 2024/06/19 14:46:27 by whaffman ### ########.fr */
/* */
/* ************************************************************************** */
/*
...Halooo dit is een zin, met woorden erin.
^ ^ ^
f->f---->b
^^ ^
ff->b
*/
#define WORD 1
#define SEP 0
#include <stdio.h>
#include <stdlib.h>
char **ft_split(char *str, char *charset);
char *ptr_skip(int word, char *str, char *sep);
int count_words(char *str, char *sep);
int is_sep(char c, char *sep);
int is_sep(char c, char *sep)
{
while (*sep)
{
if (c == *sep)
return (1);
sep++;
}
return (0);
}
int count_words(char *str, char *sep)
{
int i;
int count;
i = 0;
count = 0;
str = ptr_skip(SEP, str, sep);
while (str[i])
{
if (!is_sep(str[i], sep) \
&& (is_sep(str[i + 1], sep) \
|| str[i + 1] == '\0'))
count++;
i++;
}
return (count);
}
char *ptr_skip(int word, char *str, char *sep)
{
while (*str && word ^ is_sep(*str, sep))
str++;
return (str);
}
unsigned int ft_strlcpy(char *dest, char *src, unsigned int n)
{
unsigned int i;
i = 0;
while (src[i] && i + 1 < n)
{
dest[i] = src[i];
i++;
}
dest[i] = '\0';
return (i);
}
char **ft_split(char *str, char *charset)
{
int n_words;
char **result;
char *end;
char *word;
int i;
str = ptr_skip(SEP, str, charset);
n_words = count_words(str, charset);
result = (char **) malloc((n_words + 1) * sizeof(char *));
i = 0;
result[0] = 0;
if (!*str)
return (result);
while (i < n_words)
{
end = ptr_skip(WORD, str, charset);
word = (char *) malloc((end - str + 1) * sizeof(char));
ft_strlcpy(word, str, (end - str + 1));
word[end - str] = '\0';
result[i] = word;
str = ptr_skip(SEP, end, charset);
i++;
}
result[i] = 0;
return (result);
}
/*
#ifdef DEBUG
int main(void)
{
char **segments;
segments = ft_split("", "");
while (*segments)
{
printf("%s\n", *segments);
segments++;
}
printf("%p",*segments);
}
#endif
*/