-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
103 lines (93 loc) · 2.06 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aymoulou <aymoulou@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/08/19 18:09:38 by aymoulou #+# #+# */
/* Updated: 2021/11/12 11:10:22 by aymoulou ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int words(char *str, char c)
{
int i;
int j;
i = 0;
j = 0;
while (str[i])
{
while (str[i] == c && str[i])
i++;
if (str[i] && str[i] != c)
{
i++;
j++;
}
while (str[i] && str[i] != c)
i++;
}
return (j);
}
static void *leak(char **spl, int j)
{
j = j - 1;
while (spl[j])
{
free(spl[j]);
j--;
}
free(spl);
return (NULL);
}
static int carcts(char *str, char c)
{
int i;
i = 0;
while (str[i] && str[i] != c)
{
i++;
}
return (i);
}
static char *allocandfill(char **tab, char *src, char c)
{
int i;
int j;
int k;
j = 0;
k = 0;
while (src[k] == c)
k++;
while (j < words(src, c))
{
i = 0;
tab[j] = malloc(sizeof(char) * (carcts(&src[k], c) + 1));
if (!tab[j])
return (leak(tab, j));
while (src[k] != c && src[k])
tab[j][i++] = src[k++];
tab[j][i] = '\0';
while (src[k] == c && src[k])
k++;
j++;
}
tab[j] = NULL;
return (*tab);
}
char **ft_split(char const *s, char c)
{
int j;
char **tab;
char *str;
j = 0;
if (!s)
return (NULL);
str = (char *)s;
tab = malloc(sizeof(char *) * (words(str, c) + 1));
if (!tab)
return (NULL);
tab[j] = allocandfill(tab, str, c);
return (tab);
}