-
Notifications
You must be signed in to change notification settings - Fork 9
/
ft_split.c
119 lines (110 loc) · 2.37 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
107
108
109
110
111
112
113
114
115
116
117
118
119
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rchallie <rchallie@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/10/11 10:51:19 by rchallie #+# #+# */
/* Updated: 2019/10/23 10:19:55 by rchallie ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_hm(char const *s, char c)
{
size_t nbr;
int i;
nbr = 0;
i = 0;
while (s[i])
{
while (s[i] == c)
i++;
if (i > 0 && s[i] && s[i - 1] == c)
nbr++;
if (s[i])
i++;
}
if (nbr == 0 && s[i - 1] == c)
return (0);
if (s[0] != c)
nbr++;
return (nbr);
}
static char **ft_mal(char **strs, char const *s, char c)
{
size_t count;
int i;
int h;
count = 0;
i = 0;
h = 0;
while (s[h])
{
if (s[h] != c)
count++;
else if (h > 0 && s[h - 1] != c)
{
strs[i] = malloc(sizeof(char) * (count + 1));
if (!strs[i])
return (0);
count = 0;
i++;
}
if (s[h + 1] == '\0' && s[h] != c)
if (!(strs[i] = malloc(sizeof(char) * count + 1)))
return (0);
h++;
}
return (strs);
}
static char **ft_cpy(char **strs, char const *s, char c)
{
int i;
int j;
int h;
i = 0;
j = 0;
h = 0;
while (s[h])
{
if (s[h] != c)
strs[i][j++] = s[h];
else if (h > 0 && s[h - 1] != c)
if (h != 0)
{
strs[i][j] = '\0';
j = 0;
i++;
}
if (s[h + 1] == '\0' && s[h] != c)
strs[i][j] = '\0';
h++;
}
return (strs);
}
char **ft_split(char const *s, char c)
{
char **rtn;
int nbr_w;
if (!s || !*s)
{
if (!(rtn = malloc(sizeof(char *) * 1)))
return (NULL);
*rtn = (void *)0;
return (rtn);
}
nbr_w = ft_hm(s, c);
rtn = malloc(sizeof(char *) * (nbr_w + 1));
if (!rtn)
return (0);
if (ft_mal(rtn, s, c) != 0)
ft_cpy(rtn, s, c);
else
{
free(rtn);
return (NULL);
}
rtn[nbr_w] = (void *)0;
return (rtn);
}