-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
102 lines (93 loc) · 2.46 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kakiba <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/06/01 22:51:38 by kakiba #+# #+# */
/* Updated: 2022/07/27 15:57:37 by kakiba ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t count_split(const char *s, char c);
static size_t check_split(char **nptr, char const *s, size_t i, size_t *end);
static void create_split(char **nptr, char const *s, char c);
char **ft_split(char const *s, char c)
{
char **nptr;
if (s == NULL)
return (NULL);
nptr = ft_calloc(sizeof(char **), (count_split(s, c) + 1));
if (nptr == NULL)
return (NULL);
create_split(nptr, s, c);
return (nptr);
}
static void create_split(char **nptr, char const *s, char c)
{
size_t i;
size_t end;
size_t start;
i = 0;
start = 0;
while (s[start])
{
while (s[start] == c)
++start;
if (s[start] && ft_strchr(&s[start], c) == NULL)
{
end = ft_strlen(s);
nptr[i] = ft_substr(s, start, ft_strlen(s) - start);
start = check_split(nptr, s, i++, &end);
}
else if (s[start])
{
end = ft_strchr(&s[start], c) - s;
nptr[i] = ft_substr(s, start, end - start);
start = check_split(nptr, s, i++, &end);
}
}
if (nptr[i - 1] != NULL)
nptr[i] = 0;
}
static size_t check_split(char **nptr, char const *s, size_t i, size_t *end)
{
if (nptr[i] == NULL)
{
while (i)
{
free(nptr[i]);
nptr[i--] = NULL;
}
free(nptr[i]);
nptr[i] = NULL;
free(nptr);
nptr = NULL;
*end = ft_strlen(s);
}
return (*end);
}
static size_t count_split(char const *s, char c)
{
size_t i;
size_t j;
i = 0;
j = 0;
while (s[j])
{
while (s[j] == c)
j++;
if (s[j])
i++;
while (s[j] != c && s[j])
j++;
}
return (i);
}
/*
int main()
{
printf("%s\n", ft_split("akiba,,kyo,,suke", ',')[0]);
printf("%s\n", ft_split(",,,,akiba,,kyo,,suke,,,", ',')[0]);
}*/