-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
104 lines (93 loc) · 2.15 KB
/
ft_split.c
File metadata and controls
104 lines (93 loc) · 2.15 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aelmsafe <aelmsafe@student.1337.ma> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/11/09 05:40:31 by aelmsafe #+# #+# */
/* Updated: 2024/11/17 16:22:10 by aelmsafe ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
static size_t word_count(char const *s, char c)
{
size_t i;
size_t wc;
i = 0;
wc = 0;
while (s[i])
{
while (s[i] == c)
{
i++;
}
if (!s[i])
break ;
wc++;
while (s[i] && s[i] != c)
i++;
}
return (wc);
}
static char *word_fill(char const *s, size_t i, size_t len)
{
char *word;
word = malloc(sizeof(char) * (len + 1));
if (word == NULL)
return (NULL);
ft_strlcpy(word, &s[i - len], len + 1);
return (word);
}
static char **free_all(char **sp, size_t idx)
{
size_t i;
i = 0;
while (i <= idx)
{
free(sp[i]);
i++;
}
free(sp);
return (NULL);
}
static char **alloc_fill(char const *s, char c, size_t wc, size_t *idx)
{
char **sp;
size_t i;
size_t wlen;
sp = malloc(sizeof(char *) * (wc + 1));
if (sp == NULL)
return (NULL);
i = 0;
*idx = 0;
while (s[i])
{
while (s[i] == c)
i++;
if (!s[i])
break ;
wlen = 0;
while (s[i + wlen] && s[i + wlen] != c)
wlen++;
i += wlen;
sp[*idx] = word_fill(s, i, wlen);
if (!sp[*idx])
return (free_all(sp, *idx));
(*idx) = (*idx) + 1;
}
return (sp);
}
char **ft_split(char const *s, char c)
{
char **res;
size_t wc;
size_t idx;
if (!s)
return (NULL);
wc = word_count(s, c);
res = alloc_fill(s, c, wc, &idx);
if (res)
res[idx] = NULL;
return (res);
}