-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_strsplit.c
98 lines (89 loc) · 2.16 KB
/
ft_strsplit.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strsplit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cyfermie <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/11/07 16:07:51 by cyfermie #+# #+# */
/* Updated: 2017/11/09 16:33:30 by cyfermie ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
static size_t get_nb_str(const char *s, char c)
{
size_t nb_str;
nb_str = 0;
while (*s != '\0')
{
while (*s == c)
++s;
if (*s != '\0')
++nb_str;
while (*s != c && *s != '\0')
++s;
}
return (nb_str);
}
static int alloc_the_str(char **strsplit, const char *s, char c)
{
size_t index;
size_t nb_ch;
index = 0;
while (*s != '\0')
{
while (*s == c)
++s;
nb_ch = 0;
while (*s != c && *s != '\0')
{
++s;
++nb_ch;
}
if (nb_ch != 0)
{
strsplit[index] = (char *)malloc(sizeof(char) * (nb_ch + 1));
if (strsplit[index] == NULL)
return (0);
++index;
}
}
return (1);
}
static void fill_strsplit(char **strsplit, const char *s, char c)
{
size_t i;
size_t j;
i = 0;
while (*s != '\0')
{
while (*s == c)
++s;
j = 0;
while (*s != c && *s != '\0')
{
strsplit[i][j] = *s;
++j;
++s;
}
if (j > 0)
strsplit[i][j] = '\0';
++i;
}
}
char **ft_strsplit(char const *s, char c)
{
char **strsplit;
size_t nb_str;
if (s == NULL)
return (NULL);
nb_str = get_nb_str(s, c);
strsplit = (char **)malloc(sizeof(char *) * (nb_str + 1));
if (strsplit == NULL)
return (NULL);
strsplit[nb_str] = NULL;
if (alloc_the_str(strsplit, s, c) == 0)
return (NULL);
fill_strsplit(strsplit, s, c);
return (strsplit);
}