-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
103 lines (92 loc) · 1.46 KB
/
ft_split.c
File metadata and controls
103 lines (92 loc) · 1.46 KB
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
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
int ft_strlen(const char *s) {
return strlen(s);
}
static char *get_memory(char const *s, unsigned int start, size_t len)
{
size_t i;
i = 0;
while (s[start + i] && i < len)
i++;
return (malloc(i + 1));
}
char *ft_substr(char const *s, unsigned int start, size_t len)
{
char *sub;
size_t i;
if (!s)
return (0);
if (start < ft_strlen(s))
{
sub = get_memory(s, start, len);
if (!sub)
return (sub);
i = 0;
while (s[start] && i < len)
sub[i++] = s[start++];
sub[i] = '\0';
return (sub);
}
sub = malloc(1);
if (!sub)
return (sub);
sub[0] = 0;
return (sub);
}
static size_t ft_count(char const *s, char c)
{
int i;
int count;
i = 0;
count = 0;
while (s[i] != '\0')
{
while (s[i] && s[i] == c)
i++;
if (s[i] != '\0')
{
if ((s[i - 1] == c || i == 0))
count++;
i++;
}
}
return (count);
}
static char **free_tab(char **tab)
{
int i;
i = 0;
while (tab[i])
free(tab[i++]);
free(tab);
return (NULL);
}
char **ft_split(char const *s, char c)
{
char **tab;
size_t i;
size_t len;
i = 0;
if (!s)
return (0);
tab = (char **)malloc((ft_count(s, c) + 1) * sizeof(*tab));
if (!tab)
return (tab);
while (*s)
{
while (*s && *s == c)
s++;
len = 0;
while (s[len] && s[len] != c)
len++;
if (len != 0)
tab[i++] = ft_substr(s, 0, len);
if (!tab[i - 1] && len != 0)
return (free_tab(tab));
s += len;
}
tab[i] = NULL;
return (tab);
}