-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
93 lines (84 loc) · 1.96 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: adpachec <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/09/19 14:54:38 by adpachec #+# #+# */
/* Updated: 2022/10/03 10:00:32 by adpachec ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t ft_words(const char *s, char c)
{
size_t i;
size_t words;
words = 0;
if (s[0] == '\0')
return (0);
i = 0;
if (s[0] != c)
{
++words;
++i;
}
while (s[i])
{
if (s[i] == c && s[i + 1] != c && s[i + 1] != '\0')
++words;
++i;
}
return (words);
}
static void ft_free_res(char **res)
{
size_t i;
i = 0;
while (res[i])
{
free(res[i]);
res[i] = NULL;
++i;
}
free(res);
}
static void ft_init_matrix(const char *s, char c, char **res, size_t words)
{
size_t j;
size_t temp;
j = 0;
while (*s != '\0' && j <= words)
{
temp = 0;
while (*s == c)
++s;
while (*s != c && *s != '\0' && temp++ >= 0)
++s;
if (temp > 0)
{
res[j] = ft_substr(s - temp, 0, temp);
if (!res[j++])
{
ft_free_res(res);
return ;
}
}
}
res[j] = NULL;
}
char **ft_split(char const *s, char c)
{
size_t words;
char **res;
if (!s)
return (NULL);
words = ft_words(s, c);
res = (char **) ft_calloc(sizeof(char *), (words + 1));
if (!res)
return (NULL);
ft_init_matrix(s, c, res, words);
if (!res)
return (NULL);
return (res);
}