-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
82 lines (75 loc) · 1.96 KB
/
ft_split.c
File metadata and controls
82 lines (75 loc) · 1.96 KB
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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: joramire <joramire@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/09/28 17:37:14 by joramire #+# #+# */
/* Updated: 2022/09/30 19:42:49 by joramire ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t ft_number_of_words(char const *s, char c)
{
size_t i;
size_t size;
i = 0;
size = 0;
while (s[i] != '\0')
{
while (s[i] == c && s[i] != '\0')
i++;
if (s[i] != '\0')
size++;
while (s[i] != c && s[i] != '\0')
i++;
}
return (size);
}
static char **ft_clean(char **list, size_t i)
{
while (i > 0)
{
free(list[i]);
list[i] = NULL;
i--;
}
free(list);
list = NULL;
return (NULL);
}
static void ft_set_word(char const *s, size_t *st, size_t *end, char c)
{
while (s[*st] == c && s[*st] != '\0')
*st = *st + 1;
*end = *st;
while (s[*end] != c && s[*end] != '\0')
*end = *end + 1;
}
char **ft_split(char const *s, char c)
{
char **list;
size_t st;
size_t end;
size_t i;
list = (char **)malloc((ft_number_of_words(s, c) + 1) * sizeof(char *));
if (list == NULL)
return (NULL);
st = 0;
i = 0;
while (s[st] != '\0')
{
ft_set_word(s, &st, &end, c);
if (end != st)
{
list[i] = ft_substr(s, st, (end - st));
if (list[i] == NULL)
return (ft_clean(list, i-1));
i++;
}
st = end;
}
list[i] = NULL;
return (list);
}