-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
109 lines (98 loc) · 2.09 KB
/
ft_split.c
File metadata and controls
109 lines (98 loc) · 2.09 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
104
105
106
107
108
109
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lpierre- <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/05/31 21:08:18 by lpierre- #+# #+# */
/* Updated: 2024/05/31 21:08:19 by lpierre- ### ########.fr */
/* */
/* ************************************************************************** */
#include"libft.h"
static int count_substr(char const *s, char c)
{
int i;
int substr;
substr = 0;
if (s[0] != c && s[0] != 0)
substr++;
i = 1;
while (s[i] != 0)
{
if (s[i - 1] == c && s[i] != c)
substr++;
i++;
}
return (substr);
}
static char *ft_strndup(char const *s, int n)
{
char *dup;
int i;
dup = malloc(sizeof(char) * (n + 1));
if (dup == NULL)
{
free(dup);
return (NULL);
}
i = 0;
while (i < n)
{
dup[i] = s[i];
i++;
}
dup[i] = 0;
return (dup);
}
static void clear(char **tab)
{
int i;
i = 0;
while (tab[i])
{
free(tab[i]);
i++;
}
free(tab);
}
static char **fill_substr(char const *s, char c, char **tab)
{
int i;
int len;
int j;
i = 0;
j = 0;
while (s[i] != 0)
{
while (s[i] == c)
i++;
len = 0;
while (s[i + len] != c && s[i + len] != 0)
len++;
if (len != 0)
{
tab[j] = ft_strndup(&s[i], len);
if (!tab[j])
return (clear(tab), NULL);
j++;
}
i += len;
}
tab[j] = NULL;
return (tab);
}
char **ft_split(char const *s, char c)
{
char **tab;
int tab_len;
tab_len = count_substr(s, c);
tab = malloc(sizeof(char const *) * (tab_len + 1));
if (tab == NULL)
{
free(tab);
return (NULL);
}
tab = fill_substr(s, c, tab);
return (tab);
}