Repository navigation
Expand file tree
/
Copy pathft_split.c
More file actions
97 lines (87 loc) · 1.99 KB
/
Copy pathft_split.c
File metadata and controls
97 lines (87 loc) · 1.99 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: fcamasa <fcamasa@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2026/06/01 15:00:10 by fcamasa #+# #+# */
/* Updated: 2026/06/09 13:13:55 by fcamasa ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int count_words(char const *s, char c)
{
int i;
int words;
words = 0;
i = 0;
while (s[i] != '\0')
{
while (s[i] == c)
i++;
if (s[i] != '\0')
{
words++;
while (s[i] != '\0' && s[i] != c)
i++;
}
}
return (words);
}
static int word_len(char const *s, char c)
{
int i;
i = 0;
while (s[i] != '\0' && s[i] != c)
i++;
return (i);
}
static void free_all(char **str, int i)
{
while (i >= 0)
{
free(str[i]);
i--;
}
free(str);
}
static int fill_words(char **str, char const *s, char c)
{
int i;
int start;
int len;
i = 0;
start = 0;
while (s[i] != '\0')
{
while (s[i] == c)
i++;
if (s[i] != '\0')
{
len = word_len(s + i, c);
str[start] = ft_substr(s, i, len);
if (str[start] == NULL)
{
free_all(str, start - 1);
return (0);
}
i = i + len;
start++;
}
}
str[start] = NULL;
return (1);
}
char **ft_split(char const *s, char c)
{
char **str;
if (s == NULL)
return (NULL);
str = malloc((count_words(s, c) + 1) * sizeof(char *));
if (str == NULL)
return (NULL);
if (!fill_words(str, s, c))
return (NULL);
return (str);
}