-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
106 lines (96 loc) · 2.04 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
103
104
105
106
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: achraiti <achraiti@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/11/05 15:20:36 by achraiti #+# #+# */
/* Updated: 2023/11/11 15:17:24 by achraiti ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
void ft_free_split(char **str)
{
size_t i;
i = 0;
if (str)
{
while (str[i])
{
free(str[i]);
i++;
}
free(str);
}
}
static size_t word_count(const char *s, char c)
{
size_t count;
size_t i;
count = 0;
i = 0;
while (s[i])
{
if (s[i] != c)
{
count++;
while (s[i] && s[i] != c)
i++;
}
else
i++;
}
return (count);
}
static char *str_dup(const char *s1, char c)
{
char *scpy;
size_t slen;
size_t i;
slen = 0;
while (s1[slen] && s1[slen] != c)
slen++;
scpy = (char *)malloc((slen + 1) * sizeof(char));
if (scpy == NULL)
return (0);
i = 0;
while (i < slen)
{
scpy[i] = s1[i];
i++;
}
scpy[i] = '\0';
return (scpy);
}
int split_error(char **str)
{
ft_free_split(str);
return (1);
}
char **ft_split(char const *s, char c)
{
char **str;
size_t count;
count = word_count(s, c);
str = (char **)malloc((count + 1) * sizeof(char *));
if (!str)
return (NULL);
count = 0;
while (*s)
{
if (*s != c)
{
str[count] = str_dup(s, c);
if (str[count] == NULL && split_error(str))
return (NULL);
count++;
while (*s && *s != c)
s++;
}
else
s++;
}
str[count] = NULL;
return (str);
}