Repository navigation
Expand file tree
/
Copy pathft_split.c
More file actions
82 lines (73 loc) · 1.83 KB
/
Copy pathft_split.c
File metadata and controls
82 lines (73 loc) · 1.83 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: syokota <syokota@student.42tokyo.jp> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2026/04/25 19:51:13 by syokota #+# #+# */
/* Updated: 2026/05/01 15:27:33 by syokota ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t count_words(char const *s, char c)
{
size_t count;
size_t i;
count = 0;
i = 0;
while (s[i] != '\0')
{
if (s[i] != c && (i == 0 || s[i - 1] == c))
count++;
i++;
}
return (count);
}
static void *free_all(char **strs, size_t count)
{
size_t i;
i = 0;
while (i < count)
{
free(strs[i]);
i++;
}
free(strs);
return (NULL);
}
static char **allocate_word(char const *s, char c, char **strs)
{
size_t i;
size_t j;
size_t start;
i = 0;
j = 0;
while (s[i] != '\0')
{
if (s[i] != c)
{
start = i;
while (s[i] != '\0' && s[i] != c)
i++;
strs[j] = ft_substr(s, start, i - start);
if (!strs[j])
return (free_all(strs, j));
j++;
}
else
i++;
}
strs[j] = NULL;
return (strs);
}
char **ft_split(char const *s, char c)
{
char **strs;
if (!s)
return (NULL);
strs = malloc(sizeof(char *) * (count_words(s, c) + 1));
if (!strs)
return (NULL);
return (allocate_word(s, c, strs));
}