-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
84 lines (76 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
/* ************************************************************************** */
/* */
/* :::::::: */
/* ft_split.c :+: :+: */
/* +:+ */
/* By: rcappend <[email protected]> +#+ */
/* +#+ */
/* Created: 2020/11/09 13:45:28 by rcappend #+# #+# */
/* Updated: 2021/11/03 14:23:37 by rcappend ######## odam.nl */
/* */
/* ************************************************************************** */
#include "libft.h"
static int count_pointers(char const *s, char c)
{
unsigned int i;
i = 0;
while (*s)
{
while (*s == c)
s++;
if (*s != c && *s)
i++;
while (*s != c && *s)
s++;
}
return (i);
}
static char **free_arrays(char **s, int i)
{
while (i >= 0)
{
free(s[i]);
i--;
}
free(s);
return (NULL);
}
static char **fill_grid(char const *s, char c, char **ret, unsigned int i)
{
unsigned int j;
unsigned int k;
k = 0;
while (*s)
{
j = 0;
while (*s == c)
s++;
while (s[j] != c && s[j] != '\0')
j++;
if (k < i)
{
ret[k] = ft_substr(s, 0, j);
if (!ret[k])
return (free_arrays(ret, k));
}
k++;
while (*s != c && *s)
s++;
}
return (ret);
}
char **ft_split(char const *s, char c)
{
char **ret;
unsigned int i;
if (!s)
return (NULL);
i = count_pointers(s, c);
ret = ft_calloc(sizeof(char *), i + 1);
if (!ret)
return (NULL);
if (i == 0)
return (ret);
ret = fill_grid(s, c, ret, i);
return (ret);
}