거의 1년전
#include "libft.h"
static void free_strs(char **ret)
{
char **div;
div = ret;
while (*div != NULL)
{
free(*div);
*div++ = NULL;
}
free(ret);
ret = NULL;
}
static char **divide_str(char **div, char const *s, char c)
{
size_t len;
char const *str;
char **ret;
ret = div;
while (*s != '\0')
{
len = 0;
str = s;
while ((*s != '\0') && (*s++ != c))
len++;
*div = ft_calloc(len + 1, sizeof(char));
if (!*div)
{
free_strs(ret);
return (NULL);
}
ft_memcpy(*div, str, len);
while ((*s == c) && (*s != '\0'))
s++;
div++;
}
return (ret);
}
static size_t get_count(char const *s, char c)
{
size_t count;
if (s == NULL || *s == '\0')
return (0);
if (c == '\0')
return (1);
count = 1;
while (*s)
{
if (*s == c)
count++;
while (*s == c)
s++;
if (*s != '\0')
s++;
}
if (*--s == c)
count--;
return (count);
}
char **ft_split(char const *s, char c)
{
char **div;
size_t count;
if (s == NULL)
return (NULL);
while ((*s == c) && (*s != '\0'))
s++;
count = get_count((char *)s, c);
div = (char **)malloc(sizeof(char *) * (count + 1));
if (!div)
return (NULL);
ft_memset(div, 0, sizeof(char *) * (count + 1));
return (divide_str(div, s, c));
}
그리고 오늘
#include "libft.h"
static int get_count(char *input, const char *sep)
{
int count;
count = 0;
while (*input)
{
++count;
input += strspn(input, sep);
input += strcspn(input, sep);
}
return (count);
}
static void cleanup_tokarr(char **tokarr, int count)
{
int i;
i = -1;
while (++i < count)
free(tokarr[i]);
free(tokarr);
}
static char **fill_tokarr(char *input, const char *sep, char **tokarr)
{
char *token;
char *copy;
int i;
if (!tokarr)
return (NULL);
copy = strdup(input);
token = strtok(copy, sep);
i = 0;
while (token)
{
tokarr[i] = strdup(token);
if (!tokarr[i])
{
cleanup_tokarr(tokarr, i);
tokarr = NULL;
break ;
}
token = strtok(NULL, sep);
++i;
}
free(copy);
return (tokarr);
}
char **init_tokarr(char *input, const char *sep)
{
char **tokarr;
int count;
if (!input)
return (NULL);
count = get_count(input, sep);
tokarr = (char **)calloc(count + 1, sizeof(char *));
if (!tokarr)
return (NULL);
return (tokarr);
}
char **ft_split(char *input, const char *sep)
{
return (fill_tokarr(input, sep, init_tokarr(input, sep)));
}