-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
99 lines (88 loc) · 1.94 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: elel-yak <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/10/17 14:34:12 by elel-yak #+# #+# */
/* Updated: 2022/11/02 11:09:44 by elel-yak ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_wordlen(char const *s, char c)
{
int i;
i = 0;
while (s[i] && s[i] != c)
i++;
return (i);
}
static int ft_wordcount(char const *s, char c)
{
int i;
int w;
w = 0;
while (*s)
{
while (*s && *s == c)
s++;
i = ft_wordlen(s, c);
s += i;
if (i)
w++;
}
return (w);
}
static char *ft_wordcpy(char const *src, int n)
{
char *dest;
dest = malloc((n + 1) * sizeof(char));
if (!dest)
return (0);
dest[n] = '\0';
while (n--)
dest[n] = src[n];
return (dest);
}
static char **ft_free(char **str, size_t n)
{
size_t i;
i = 0;
while (i < n)
{
free(str[i]);
str[i] = NULL;
i++;
}
free(str);
str = NULL;
return (0);
}
char **ft_split(char const *s, char c)
{
char **t;
int size;
int i;
int n;
if (!s)
return (0);
size = ft_wordcount(s, c);
t = malloc((size + 1) * sizeof(char *));
if (!t)
return (0);
i = -1;
while (++i < size)
{
while (*s && *s == c)
s++;
n = ft_wordlen(s, c);
if (*s)
t[i] = ft_wordcpy(s, n);
if (!t[i])
return (ft_free(t, i));
s += n;
}
t[size] = 0;
return (t);
}