-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_split.c
89 lines (81 loc) · 1.83 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tedison <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/02 15:40:58 by tedison #+# #+# */
/* Updated: 2021/04/07 18:17:18 by tedison ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
int word_count(char const *s, char c, int *p, int *p2)
{
size_t i;
size_t count;
*p = 0;
*p2 = 0;
i = 0;
count = 0;
while (s[i])
{
if (s[i] != c)
{
while (s[i] != c && s[i])
i++;
count++;
}
if (s[i] != 0)
i++;
}
return (count);
}
int ft_malloc(char ***tab, int i)
{
*tab = malloc(i);
if (*tab == NULL)
{
return (0);
}
return (1);
}
char **ft_freetab(char **tab, int j)
{
int i;
i = 0;
while (j >= 0)
{
free(tab[j]);
j--;
}
free(tab);
return (NULL);
}
char **ft_split(char const *s, char c)
{
char **tab;
int i;
int j;
int start;
if (!s)
return (NULL);
if (!(ft_malloc(&tab, sizeof(*tab) * (word_count(s, c, &i, &j) + 1))))
return (NULL);
while (s[i])
{
if (s[i] != c)
{
start = i;
while (s[i] != c && s[i])
i++;
tab[j] = ft_substr(s, start, (i - start));
if (!tab[j++])
return (ft_freetab(tab, j - 1));
}
if (s[i] != 0)
i++;
}
tab[j] = NULL;
return (tab);
}