-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
95 lines (85 loc) · 2.09 KB
/
ft_split.c
File metadata and controls
95 lines (85 loc) · 2.09 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: sel-abbo <sel-abbo@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/10/29 00:00:08 by sel-abbo #+# #+# */
/* Updated: 2024/11/08 18:27:38 by sel-abbo ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_len(const char *s, char c)
{
int i;
i = 0;
while (s[i] && s[i] != c)
i++;
return (i);
}
static int count_word(char *str, char c)
{
int i;
int count;
count = 0;
i = 0;
if (str[i] == 0)
return (0);
while (str[i] == c && str[i])
i++;
while (str[i])
{
if (str[i] == c && str[i - 1] != c)
count++;
i++;
}
if (str[i - 1] != c)
count++;
return (count);
}
static void ft_free_all(char **res, int h)
{
while (h >= 0)
free(res[h--]);
}
char **ft_split(char const *s, char c)
{
char **res;
int i;
int j;
i = 0;
res = malloc((count_word((char *)s, c) + 1) * sizeof(char *));
if (!res)
return (NULL);
while (*s)
{
if (*s == c)
s++;
else
{
j = 0;
res[i] = malloc((ft_len(s, c) + 1) * sizeof(char));
if (!res[i])
return (ft_free_all(res, i), NULL);
while (*s && *s != c)
res[i][j++] = *s++;
res[i++][j] = '\0';
}
}
return (res[i] = NULL, res);
}
// #include <stdio.h>
// int main()
// {
// char **result;
// int i;
// result = ft_split(",,,,Hello,,world,,this,is,a,test,,,,,,,,ffff,,", ',');
// i = 0;
// while (result[i])
// {
// printf("%s \n", result[i]);
// i++;
// }
// printf("%s \n", result[i]);
// }