-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_split.c
108 lines (97 loc) · 2.14 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
107
108
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tbrebion <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/24 16:35:24 by tbrebion #+# #+# */
/* Updated: 2021/12/07 13:39:19 by tbrebion ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int count_char(char const *str, char c)
{
int i;
i = 0;
while (str[i] && str[i] != c)
i++;
return (i);
}
static void malloc_error(char **tab, int len)
{
int i;
i = 0;
while (i <= len + 1)
{
free(tab[i]);
i++;
}
free(tab);
}
static char *new_strdup(char const *str, char c)
{
int i;
char *res;
i = 0;
res = malloc(sizeof(char) * (count_char(str, c) + 1));
if (res == NULL)
return (NULL);
while (str[i] && str[i] != c)
{
res[i] = str[i];
i++;
}
res[i] = '\0';
return (res);
}
static void for_my_split(char **res, char const *s, char c, int len)
{
int i;
int j;
i = 0;
j = 0;
while (j < len)
{
while (s[i] == c)
i++;
if (s[i])
{
res[j] = new_strdup(&s[i], c);
if (res[j] == NULL)
{
malloc_error(res, len);
return ;
}
i += count_char(&s[i], c);
j++;
}
while (s[i] && s[i] != c)
i++;
}
res[j] = NULL;
}
char **ft_split(char const *s, char c)
{
int i;
int len;
char **res;
i = 0;
len = 0;
if (s == NULL)
return (NULL);
while (s[i])
{
while (s[i] && s[i] == c)
i++;
if (s[i] && s[i] != c)
len++;
while (s[i] && s[i] != c)
i++;
}
res = malloc(sizeof(char *) * (len + 1));
if (res == NULL)
return (NULL);
for_my_split(res, s, c, len);
return (res);
}