Repository navigation
Expand file tree
/
Copy pathft_split.c
More file actions
102 lines (92 loc) · 2.12 KB
/
Copy pathft_split.c
File metadata and controls
102 lines (92 loc) · 2.12 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: seukim <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/12/21 16:00:23 by seukim #+# #+# */
/* Updated: 2026/02/12 16:53:52 by seukim ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int count_words(const char *s, char c)
{
int count;
int i;
count = 0;
i = 0;
while (s[i])
{
if (s[i] == c)
i++;
else
{
count++;
while (s[i] && s[i] != c)
i++;
}
}
return (count);
}
static char **free_all(char **result, int i)
{
while (i > 0)
{
i--;
free(result[i]);
}
free(result);
return (NULL);
}
static char **fill_res(char const *s, char c, char **res)
{
int i;
int j;
int start;
i = 0;
j = 0;
while (s[i])
{
while (s[i] && s[i] == c)
i++;
if (s[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 - 1));
}
}
res[j] = NULL;
return (res);
}
char **ft_split(char const *s, char c)
{
char **res;
if (!s)
return (NULL);
res = malloc(sizeof(char *) * (count_words(s, c) + 1));
if (!res)
return (NULL);
return (fill_res(s, c, res));
}
//int main(void)
//{
// char **result;
// int i;
// i = 0;
// result = ft_split(" Hello 42 gs Good ", ' ');
// if (!result)
// return (1);
// while (result[i])
// {
// printf("row [%d]: %s\n", i, result[i]);
// free(result[i]);
// i++;
// }
// free(result);
// return (0);
//}