-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_split.c
81 lines (73 loc) · 1.93 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ssoares- <ssoares-@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/07/13 03:11:24 by ssoares- #+# #+# */
/* Updated: 2022/07/21 15:39:21 by ssoares- ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t ft_size_array(const char *s, char c)
{
int is_new_word;
size_t words;
is_new_word = 0;
words = 0;
while (*s)
{
if (is_new_word == 0 && *s != c)
{
is_new_word = 1;
words++;
}
else if (is_new_word == 1 && *s == c)
is_new_word = 0;
s++;
}
return (words);
}
static size_t ft_size_word(const char *s, char c)
{
size_t i;
i = 0;
while (s[i] && s[i] != c)
i++;
return (i);
}
static void *ft_free_mat(char **tab, size_t limit)
{
while (limit--)
free(tab[limit]);
free(tab);
return (NULL);
}
char **ft_split(char const *s, char c)
{
char **mat;
size_t len;
size_t size_array;
size_t counter;
if (!s)
return (NULL);
size_array = ft_size_array(s, c);
mat = (char **)malloc(sizeof(char *) * (size_array + 1));
if (!mat)
return (NULL);
counter = 0;
while (counter < size_array)
{
len = ft_size_word(s, c);
if (len > 0)
{
mat[counter] = ft_substr(s, 0, len);
if (mat[counter++] == NULL)
return (ft_free_mat(mat, counter - 1));
}
s += len + 1;
}
mat[counter] = NULL;
return (mat);
}