-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
119 lines (108 loc) · 2.11 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: hnabil <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/11/13 15:41:22 by hnabil #+# #+# */
/* Updated: 2019/11/13 16:14:14 by hnabil ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static char **ft_fr(char **tab, int i)
{
int a;
a = 0;
while (a <= i)
{
free(tab[a]);
a++;
}
free(tab);
return (NULL);
}
static int ft_calcul_mot(char const *s, char c)
{
int i;
int j;
i = 0;
j = 0;
while (s[i])
{
if (s[i] != c)
{
j++;
while (s[i] && s[i] != c)
i++;
}
else
i++;
}
return (j);
}
static char **ft_alloc(char **t, char const *s, char c, int n)
{
int i;
int k;
int j;
i = 0;
j = 0;
while (i < n && s[j])
{
k = 0;
while (s[j] && s[j] != c)
{
k++;
j++;
}
if (k != 0)
{
if (!(t[i] = (char *)malloc(sizeof(char) * (k + 1))))
return (ft_fr(t, i));
i++;
}
j++;
}
t[n] = 0;
return (t);
}
static void ft_remp(char **t, char const *s, char c, int n)
{
int i;
int j;
int k;
i = 0;
j = 0;
while (i < n && s[j])
{
k = 0;
if (s[j] != c)
{
while (s[j] && s[j] != c)
{
t[i][k] = s[j];
k++;
j++;
}
t[i][k] = '\0';
i++;
}
else
j++;
}
}
char **ft_split(char const *s, char c)
{
int n;
char **t;
if (s == NULL)
return (0);
n = ft_calcul_mot(s, c);
if (!(t = (char **)malloc(sizeof(char *) * (n + 1))))
return (0);
if (!(t = ft_alloc(t, s, c, n)))
return (0);
ft_remp(t, s, c, n);
return (t);
}