-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
103 lines (93 loc) · 2.12 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: pmaryjo <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/09/05 18:41:51 by pmaryjo #+# #+# */
/* Updated: 2021/09/05 18:41:51 by pmaryjo ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static void free_arr(char ***array, int size)
{
int i;
i = 0;
while (i < size)
{
free((*array)[i++]);
}
free(*array);
}
static int get_str_cnt(char const *s, char c)
{
int i;
int count;
i = 0;
count = 0;
while (s[i])
{
while (s[i] == c)
i++;
if (s[i] == '\0')
break ;
while (s[i] != c && s[i] != '\0')
i++;
count++;
}
return (count);
}
static char *get_string(char const *s, char c, int begin)
{
int i;
int end;
char *str;
i = 0;
end = begin;
while (s[end] != c && s[end] != '\0')
end++;
str = (char *)malloc(end - begin + 1);
if (!str)
return (NULL);
while (begin + i != end)
{
str[i] = s[i + begin];
i++;
}
str[i] = '\0';
return (str);
}
static char **get_arr(const char *s, char c)
{
if (!s)
return (NULL);
return ((char **)malloc((get_str_cnt(s, c) + 1) * sizeof(char **)));
}
char **ft_split(char const *s, char c)
{
int i;
int j;
char **array;
array = get_arr(s, c);
if (!array)
return (NULL);
i = 0;
j = 0;
while (s[i])
{
while (s[i] == c)
i++;
if (s[i] == '\0')
break ;
array[j++] = get_string(s, c, i);
if (array[j - 1] == NULL)
{
free_arr(&array, j - 1);
return (NULL);
}
i += ft_strlen(array[j - 1]);
}
array[j] = NULL;
return (array);
}