-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
89 lines (80 loc) · 1.89 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mel-mouh <mel-mouh@student.1337.ma> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/10/27 20:46:46 by mel-mouh #+# #+# */
/* Updated: 2024/11/06 17:07:46 by mel-mouh ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static char **ft_free(char **strs, int j)
{
int i;
i = 0;
while (i <= j)
{
free(strs[i]);
i++;
}
free(strs);
return (NULL);
}
static int count_word(char const *s, char c)
{
int i;
int words;
i = 0;
words = 0;
while (s[i] != '\0')
{
while (s[i] == c)
i++;
if (s[i] != '\0')
{
words++;
while (s[i] != '\0' && s[i] != c)
i++;
}
}
return (words);
}
static char **filler(char **strs, char c, char const *s)
{
int i;
int j;
int start;
i = 0;
j = 0;
while (s[j] != '\0')
{
while (s[j] == c)
j++;
if (s[j])
{
start = j;
while (s[j] != c && s[j])
j++;
strs[i] = ft_substr(s, start, j - start);
if (strs[i] == NULL)
return (ft_free(strs, i));
i++;
}
}
strs[i] = NULL;
return (strs);
}
char **ft_split(char const *s, char c)
{
char **strs;
int words;
if (s == NULL)
return (NULL);
words = count_word(s, c);
strs = (char **)malloc((words + 1) * (sizeof(char *)));
if (strs == NULL)
return (NULL);
return (filler(strs, c, s));
}