-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_split.c
104 lines (93 loc) · 1.99 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bcaffere <[email protected] +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/05/01 19:37:15 by bcaffere #+# #+# */
/* Updated: 2021/05/05 20:50:12 by bcaffere ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t words_count(char *s, char c)
{
size_t i;
size_t j;
i = 0;
j = 0;
while (*s)
{
if (*s != c)
i++;
else if (*s == c && i != 0)
{
j++;
i = 0;
}
s++;
}
if (i != 0)
j++;
return (j);
}
static char *word(char *s, char c)
{
char *buf;
while (*s == c)
s++;
buf = s;
while (*buf && *buf != c)
buf++;
*buf = '\0';
return (ft_strdup(s));
}
static char **free_arr(char **arr, char *s)
{
size_t i;
i = 0;
while (arr[i])
{
free(arr[i]);
i++;
}
free(arr);
free(s);
return (NULL);
}
static char **worker(char **arr, char *s1, char c, size_t j)
{
size_t i;
char *str;
str = s1;
i = 0;
while (i < j)
{
if (*s1 != c)
{
arr[i] = word(s1, c);
if (!arr[i])
return (free_arr(arr, s1));
s1 = s1 + ft_strlen(arr[i]);
i++;
}
s1++;
}
arr[i] = NULL;
free(str);
return (arr);
}
char **ft_split(char const *s, char c)
{
char **w_arr;
char *s1;
size_t j;
s1 = ft_strdup(s);
if (!s1)
return (NULL);
j = words_count(s1, c);
w_arr = (char **)malloc(sizeof(char *) * (j + 1));
if (!w_arr)
return (NULL);
return (worker(w_arr, s1, c, j));
}