Repository navigation
Expand file tree
/
Copy pathft_split.c
More file actions
76 lines (69 loc) · 1.77 KB
/
Copy pathft_split.c
File metadata and controls
76 lines (69 loc) · 1.77 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: danrodr3 <danrodr3@students.42madrid.com> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/10/13 17:44:28 by danrodr3 #+# #+# */
/* Updated: 2025/10/13 17:46:51 by danrodr3 ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int count_words(char const *s, char c)
{
int i;
int w;
i = 0;
w = 0;
while (s[i])
{
if ((s[i] != c) && (i == 0 || s[i - 1] == c))
w++;
i++;
}
return (w);
}
static void free_split(char **res, int j)
{
while (--j >= 0)
free(res[j]);
free(res);
}
static char **fill_split(char const *s, char c, char **res, int words)
{
int i;
int j;
int start;
i = 0;
j = 0;
while (s[i] && j < words)
{
while (s[i] == c)
i++;
start = i;
while (s[i] && s[i] != c)
i++;
if (i > start)
{
res[j] = ft_substr(s, start, i - start);
if (!res[j])
return (free_split(res, j), NULL);
j++;
}
}
res[j] = 0;
return (res);
}
char **ft_split(char const *s, char c)
{
char **res;
int words;
if (!s)
return (NULL);
words = count_words(s, c);
res = malloc(sizeof(char *) * (words + 1));
if (!res)
return (NULL);
return (fill_split(s, c, res, words));
}