-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
102 lines (92 loc) · 2 KB
/
ft_split.c
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: jeshin <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/10/06 18:13:17 by jeshin #+# #+# */
/* Updated: 2023/10/21 19:19:52 by jeshin ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
size_t word_count(char const *s, char c)
{
size_t ret;
int i;
ret = 0;
i = 0;
if (s[i] && s[i] != c)
ret++;
while (s[i])
{
if (s[i] == c && (s[i + 1] != c && s[i + 1] != 0))
ret++;
i++;
}
return (ret);
}
char *ft_strdup_till_c(const char **s, char c)
{
char *ret;
int i;
i = 0;
while ((*s)[i] && (*s)[i] != c)
i++;
ret = (char *)malloc(sizeof(char) * (i + 1));
if (!ret)
return (0);
i = 0;
while (**s && **s != c)
{
ret[i] = **s;
(*s)++;
i++;
}
ret[i] = 0;
return (ret);
}
void is_deli(char const **s, char c)
{
while (**s && **s == c)
(*s)++;
}
void arr_clear_all(char **arr, int size)
{
int i;
i = 0;
while (i < size)
{
free(arr[i]);
arr[i] = 0;
i++;
}
free(arr);
arr = 0;
}
char **ft_split(char const *s, char c)
{
char **ret;
char *str;
int i;
ret = (char **)malloc(sizeof(char *) * (word_count(s, c) + 1));
if (!ret)
return (0);
i = 0;
while (*s)
{
is_deli(&s, c);
if (*s && (*s != c))
{
str = ft_strdup_till_c(&s, c);
if (!str)
{
arr_clear_all(ret, i);
return (0);
}
ret[i++] = str;
}
}
ret[i] = 0;
return (ret);
}