-
Notifications
You must be signed in to change notification settings - Fork 4
/
ft_split.c
78 lines (71 loc) · 1.72 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ykoh <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/04/15 17:14:05 by ykoh #+# #+# */
/* Updated: 2020/10/06 02:18:40 by ykoh ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t ft_splitcnt(char const *s, char c)
{
char flg;
size_t cnt;
if (!s)
return (0);
cnt = 0;
flg = 1;
while (*s)
{
if (*s == c)
flg = 1;
else
{
(flg == 1) ? cnt++ : cnt;
flg = 0;
}
s++;
}
return (cnt);
}
static void ft_freeall(char **ret)
{
int i;
i = 0;
while (ret[i])
{
free(ret[i]);
i++;
}
free(ret);
}
char **ft_split(char const *s, char c)
{
const size_t splitcnt = ft_splitcnt(s, c);
const char *p = s;
char **ret;
char *end;
size_t i;
if (!s || !(ret = ft_calloc(splitcnt + 1, sizeof(char *))))
return (NULL);
i = 0;
while (i < splitcnt)
{
if (*s != c)
{
if (!(end = ft_strchr(s, c)))
end = (char *)p + ft_strlen(p);
if (!(ret[i++] = ft_strndup(s, end - s)))
{
ft_freeall(ret);
return (NULL);
}
s = end;
}
s++;
}
return (ret);
}