-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
95 lines (86 loc) · 2.07 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: matesant <matesant@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/08/06 09:47:21 by matesant #+# #+# */
/* Updated: 2023/08/13 15:21:35 by matesant ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_count_words(char const *s, char c)
{
size_t words;
words = 0;
while (*s != '\0')
{
if (*s == c)
s++;
else
{
words++;
while (*s != '\0' && *s != c)
s++;
}
}
return (words);
}
static void ft_erase(char **array)
{
int count;
count = 0;
if (!array)
return ;
while (array[count])
{
if (array[count] != NULL)
{
free(array[count]);
array[count] = NULL;
}
count++;
}
free(array);
}
static char **ft_allocate(char **array, const char *s, char c)
{
int word_len;
size_t i;
i = 0;
while (*s)
{
word_len = 0;
while (s[word_len] != c && s[word_len])
word_len++;
array[i] = (char *)ft_calloc((word_len + 1), sizeof(char));
if (array[i] == NULL)
{
ft_erase(array);
return (NULL);
}
ft_strlcpy(array[i], s, word_len + 1);
i++;
while (*s != c && *s)
s++;
while (*s == c && *s)
s++;
}
array[i] = NULL;
return (array);
}
char **ft_split(char const *s, char c)
{
int words;
char **array;
if (!(s))
return (NULL);
words = ft_count_words(s, c);
array = (char **)ft_calloc((words + 1), sizeof(char *));
if (!(array))
return (NULL);
while (*s == c && *s)
s++;
return (ft_allocate(array, s, c));
}