-
Notifications
You must be signed in to change notification settings - Fork 1
/
ft_split.c
94 lines (84 loc) · 2.08 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: yuotsuka <yuotsuka@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/04/18 21:04:01 by yuotsuka #+# #+# */
/* Updated: 2024/05/03 18:17:13 by yuotsuka ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t ft_count_words(char const *s, char c)
{
size_t count;
size_t i;
count = 0;
i = 0;
while (*(s + i))
{
if (*(s + i) != c)
{
count++;
while (*(s + i) && *(s + i) != c)
i++;
}
else if (*(s + i) == c)
i++;
}
return (count);
}
static size_t ft_get_wordlen(char const *s, char c)
{
size_t i;
i = 0;
while (*(s + i) && *(s + i) != c)
i++;
return (i);
}
static void free_array(size_t i, char **array)
{
while (i > 0)
{
i--;
free(*(array + i));
}
free(array);
}
static char **ft_fsplit(char const *s, char c, char **array, size_t words_count)
{
size_t i;
size_t j;
i = 0;
j = 0;
while (i < words_count)
{
while (*(s + j) && *(s + j) == c)
j++;
*(array + i) = ft_substr(s, j, ft_get_wordlen(&*(s + j), c));
if (!*(array + i))
{
free_array(i, array);
return (NULL);
}
while (*(s + j) && *(s + j) != c)
j++;
i++;
}
*(array + i) = NULL;
return (array);
}
char **ft_split(char const *s, char c)
{
char **array;
size_t words;
if (!s)
return (NULL);
words = ft_count_words(s, c);
array = (char **)malloc(sizeof(char *) * (words + 1));
if (!array)
return (NULL);
array = ft_fsplit(s, c, array, words);
return (array);
}