-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_split.c
94 lines (84 loc) · 2 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mmoumni <mmoumni@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/20 09:09:56 by mbabela #+# #+# */
/* Updated: 2022/01/02 17:10:11 by mmoumni ### ########.fr */
/* */
/* ************************************************************************** */
#include "fdf.h"
int ft_words(const char *s, char c)
{
int i;
i = 0;
while (*s != '\0')
{
if (*s != c && (*(s + 1) == c || *(s + 1) == '\0'))
i++;
s++;
}
return (i);
}
static int word_size(const char *s, char c)
{
int i;
i = 0;
while (*(s + i) != '\0' && *(s + i) != c)
{
i++;
}
return (i);
}
static char *fill_str(char *lil_str, const char *s, char c)
{
int i;
i = 0;
while (*s != '\0' && *s != c)
{
*(lil_str + i) = *s;
i++;
s++;
}
*(lil_str + i) = '\0';
return (lil_str);
}
static void *free_f(char **str, int i)
{
while (i >= 0)
{
free(str + i);
i--;
}
free(str);
return (NULL);
}
char **ft_split(char *s, char c)
{
char **tab;
int i;
int words;
if (s == NULL)
return (NULL);
words = ft_words(s, c);
tab = (char **)malloc(sizeof(char *) * (words + 1));
if (tab == 0)
return (NULL);
i = 0;
while (i < words)
{
while (*s == c && *s != '\0')
s++;
*(tab + i) = (char *)malloc(sizeof(char) * (word_size((s), c) + 1));
if (*(tab + i) == 0)
return (free_f(tab, i));
fill_str(*(tab + i), s, c);
while (*s != c && *s != '\0')
s++;
i++;
}
*(tab + i) = 0;
return (tab);
}