-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_split.c
106 lines (95 loc) · 2.17 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
103
104
105
106
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: amahla <amahla@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/05/02 12:34:09 by amahla #+# #+# */
/* Updated: 2022/05/03 10:40:26 by amahla ### ########.fr */
/* */
/* ************************************************************************** */
#include"libft.h"
static void free_array(char **split, int y)
{
int i;
i = 0;
while (i < y)
free(split[i++]);
free(split);
}
static int count_wd(char const *s, char c)
{
size_t i;
int count;
i = 0;
count = 0;
if (!s || !*s)
return (0);
while (*(s + i))
{
while (*(s + i) && *(s + i) == c)
i++;
if (*(s + i))
count++;
while (*(s + i) && *(s + i) != c)
i++;
}
return (count);
}
static size_t slen_wd(char const *s, char c)
{
size_t i;
i = 0;
while (*(s + i) && *(s + i) != c)
i++;
return (i);
}
static void strscpy(char **split, char const *s, char c)
{
size_t y;
size_t x;
size_t i;
i = 0;
y = 0;
while (s && *(s + i))
{
x = 0;
while (*(s + i) && *(s + i) == c)
i++;
while (*(s + i) && *(s + i) != c)
{
*(split[y] + x) = *(s + i);
x++;
i++;
}
y++;
}
}
char **ft_split(char const *s, char c)
{
size_t i;
int y;
char **split;
y = -1;
i = 0;
split = ft_calloc((count_wd(s, c) + 1), sizeof(char *));
if (!split)
return (NULL);
while (++y < count_wd(s, c) && s)
{
while (*(s + i) && *(s + i) == c)
i++;
split[y] = ft_calloc((slen_wd(s + i, c) + 1), sizeof(char));
if (!split[y])
{
free_array(split, y);
return (NULL);
}
while (*(s + i) && *(s + i) != c)
i++;
}
strscpy(split, s, c);
split[y] = NULL;
return (split);
}