-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
96 lines (87 loc) · 1.99 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: eagoumi <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/10/24 04:04:51 by eagoumi #+# #+# */
/* Updated: 2022/11/08 20:31:23 by eagoumi ### ########.fr */
/* */
/* ************************************************************************** */
#include "./libft.h"
int ft_count(char const *string, char c)
{
int i;
int count;
i = 0;
count = 0;
while (string[i])
{
while (string[i] == c && string[i])
{
i++;
}
if (string[i])
{
count++;
}
while (string[i] && string[i] != c)
{
i++;
}
}
return (count);
}
char **free_str(char **string)
{
int i;
i = 0;
while (string[i])
{
free(string[i]);
i++;
}
free(string);
return (NULL);
}
char **check_if_empty_and_allocate(char const *s, char c)
{
char **one_case;
if (!s)
return (NULL);
if (!*s)
{
one_case = (char **)malloc(sizeof(char *));
if (one_case)
one_case[0] = NULL;
return (one_case);
}
else
return ((char **)malloc((ft_count(s, c) + 1) * sizeof(char *)));
}
char **ft_split(char const *s, char c)
{
int i;
int k;
int y;
char **big;
i = 0;
y = 0;
big = check_if_empty_and_allocate(s, c);
while (big && s[i] != '\0')
{
while (s[i] == c)
i++;
k = 0;
while (s[i + k] && s[i + k] != c)
k++;
if (k != 0)
big[y++] = ft_substr(s, i, k);
if (y > 0 && big[y - 1] == NULL)
return (free_str(big));
i = k + i;
big[y] = NULL;
}
return (big);
}