-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
83 lines (74 loc) · 1.82 KB
/
Copy pathft_split.c
File metadata and controls
83 lines (74 loc) · 1.82 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
83
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: refernan <refernan@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2026/06/04 08:37:34 by refernan #+# #+# */
/* Updated: 2026/06/04 08:43:30 by refernan ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int count_words(char const *s, char c)
{
int count;
int i;
count = 0;
i = 0;
while (s[i])
{
while (s[i] && s[i] == c)
i++;
if (s[i])
count++;
while (s[i] && s[i] != c)
i++;
}
return (count);
}
static char **free_all(char **res)
{
int i;
i = 0;
while (res[i])
{
free(res[i]);
i++;
}
free(res);
return (NULL);
}
static char **fill_split(char const *s, char c, char **res, int words)
{
size_t i;
int j;
size_t start;
i = 0;
j = 0;
while (j < words)
{
while (s[i] && s[i] == c)
i++;
start = i;
while (s[i] && s[i] != c)
i++;
res[j] = ft_substr(s, start, i - start);
if (!res[j])
return (free_all(res));
j++;
}
return (res);
}
char **ft_split(char const *s, char c)
{
char **res;
int words;
if (s == NULL)
return (NULL);
words = count_words(s, c);
res = ft_calloc(words + 1, sizeof(char *));
if (res == NULL)
return (NULL);
return (fill_split(s, c, res, words));
}