-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_split.c
80 lines (71 loc) · 1.85 KB
/
ft_split.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: chanheki <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/07/12 02:16:10 by chanheki #+# #+# */
/* Updated: 2022/07/25 20:06:08 by chanheki ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t word_count(char const *s, char c)
{
size_t count;
count = 0;
while (*s)
{
if (*s != c && (*(s + 1) == c || *(s + 1) == '\0'))
count++;
s++;
}
return (count);
}
static char *copy_one(char const *s, char c)
{
size_t len;
char *word;
len = ft_strlen(s);
if (ft_strchr(s, c))
len = (size_t)(ft_strchr(s, c) - s);
word = malloc(sizeof(char) * (len + 1));
if (!word)
return (NULL);
ft_strlcpy(word, s, len + 1);
return (word);
}
static void free_all(char **words)
{
char **ptr;
ptr = words;
while (*ptr)
free(*(ptr++));
free(words);
}
char **ft_split(char const *s, char c)
{
size_t i;
char **words;
if (!s)
return (NULL);
words = (char **)ft_calloc(word_count(s, c) + 1, sizeof(char *));
i = 0;
while (words && *s)
{
if (*s == c)
s++;
else
{
*(words + i) = copy_one(s, c);
if (*(words + i) == NULL)
{
free_all(words);
return (NULL);
}
s += ft_strlen(*(words + i));
i++;
}
}
return (words);
}