-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
112 lines (100 loc) · 2.32 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: emdi-mar <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/11/08 21:55:10 by emdi-mar #+# #+# */
/* Updated: 2024/11/08 21:55:48 by emdi-mar ### ########.fr */
/* */
/* ************************************************************************** */
/*
** LIBRARY: libft
** SYNOPSIS: split string, with specified character as delimiter, into an array
** of strings
**
** DESCRIPTION:
** Allocates (with malloc(3)) and returns an array of strings obtained by
** splitting ’s’ using the character ’c’ as a delimiter. The array must be
** ended by a NULL pointer.
*/
#include "libft.h"
static size_t count_words(char const *s, char c)
{
size_t i;
int trig;
i = 0;
trig = 0;
while (*s)
{
if (*s != c && !trig)
{
trig = 1;
i++;
}
else if (*s == c)
trig = 0;
s++;
}
return (i);
}
static size_t count_symbols(char const *s, char c)
{
size_t i;
i = 0;
while (s[i] && s[i] != c)
i++;
return (i);
}
static size_t free_all(char **p)
{
size_t i;
size_t trig;
i = 0;
trig = 2;
while (p[i])
{
free(p[i]);
i++;
}
free(p);
return (trig);
}
static size_t malloc_write_word(size_t len, char **p, char const *s)
{
size_t trig;
trig = 1;
while (*p)
p++;
*p = ft_calloc(len + 1, sizeof(**p));
if (*p)
ft_strlcpy(*p, s, len + 1);
else
trig = free_all(p);
return (trig);
}
char **ft_split(char const *s, char c)
{
char **p;
size_t i;
size_t trig;
p = NULL;
trig = 0;
p = ft_calloc(count_words(s, c) + 1, sizeof(*p));
if (s && p)
{
i = 0;
while (s[i] && trig != 2)
{
if (s[i] != c && trig == 0)
trig = malloc_write_word(count_symbols(&s[i], c), p, &s[i]);
else if (s[i] == c)
trig = 0;
i++;
}
if (trig == 2)
p = NULL;
}
return (p);
}