-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
98 lines (89 loc) · 2.05 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
95
96
97
98
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ide-spir <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/01/06 15:52:02 by ide-spir #+# #+# */
/* Updated: 2022/01/19 12:08:07 by ide-spir ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t count_strings(const char *s, char c)
{
size_t nb_strings;
nb_strings = 0;
while (*s != '\0')
{
if (*s != c)
{
while (*s != '\0' && *s != c)
s++;
nb_strings++;
continue ;
}
s++;
}
return (nb_strings);
}
static const char *dup_until_c(char **cpy, const char *src, char c)
{
size_t len;
size_t i;
while (*src == c)
src++;
len = 0;
while (src[len] != '\0' && src[len] != c)
len++;
*cpy = (char *)malloc(sizeof(char) * (len + 1));
if (!cpy)
return (NULL);
i = 0;
while (i < len)
{
(*cpy)[i] = src[i];
i++;
}
(*cpy)[i] = '\0';
src += len + 1;
return (src);
}
static void free_strs(char ***strs, size_t len)
{
size_t i;
i = 0;
while (i < len)
{
free((*strs)[i]);
i++;
}
free(*strs);
*strs = NULL;
}
char **ft_split(const char *s, char c)
{
char **strs;
size_t nb_strings;
size_t i;
if (!s)
return (NULL);
nb_strings = count_strings(s, c);
strs = (char **)malloc(sizeof(char *) * (nb_strings + 1));
if (strs)
{
strs[nb_strings] = NULL;
i = 0;
while (i < nb_strings)
{
s = dup_until_c(strs + i, s, c);
if (!s)
{
free_strs(&strs, i);
break ;
}
i++;
}
}
return (strs);
}