-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
90 lines (82 loc) · 2.09 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: atabiti <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/17 16:05:14 by atabiti #+# #+# */
/* Updated: 2021/11/23 10:30:20 by atabiti ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static char *ccleaner(char **arr)
{
int i;
i = 0;
while (arr[i])
{
free(arr[i++]);
}
free(arr);
return (NULL);
}
static char *fsubstr(char const *s, unsigned int start, size_t len, char **arr)
{
char *substr;
if (!s)
return (NULL);
if (start >= (size_t)ft_strlen(s))
return (ft_strdup(""));
if (len > ft_strlen(s + start))
len = ft_strlen(s + start);
substr = (char *) malloc (len + 1);
if (!substr)
return (ccleaner(arr));
ft_strlcpy(substr, s + start, len + 1);
return (substr);
}
static size_t countblocks(char const *s1, char delimiter)
{
size_t l;
l = 0;
while (*s1 != '\0')
{
if (*s1 != delimiter)
{
l++;
while (*s1 != '\0' && *s1 != delimiter)
s1++;
}
else
s1++;
}
return (l);
}
char **ft_split(char const *s, char c)
{
size_t index;
size_t i;
char **ptr;
const char *spl;
i = 0;
if (!s)
return (NULL);
ptr = (char **) malloc (sizeof(char *) * (countblocks(s, c) + 1));
if (!ptr)
return (NULL);
while (*s != '\0')
{
while (*s != '\0' && *s == c)
s++;
spl = s;
index = 0;
while (s[index] && s[index] != c)
index++;
s = s + index;
if (*(s - 1) != c)
ptr[i++] = fsubstr(spl, 0, index, ptr);
}
ptr[i] = NULL;
return (ptr);
}