-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_split.c
79 lines (72 loc) · 1.92 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: johnavar <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/05/04 13:15:24 by johnavar #+# #+# */
/* Updated: 2024/02/07 09:15:31 by sebasnadu ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../include/libft.h"
static inline int words_counter(const char *s, char c)
{
int i;
int counter;
i = 0;
counter = 0;
while (s[i])
{
while (s[i] == c)
i++;
if (s[i])
counter++;
while ((s[i] != c) && s[i])
i++;
}
return (counter);
}
static int word_dup(const char *src, char **dst, char c)
{
int i;
int size;
size = 0;
while ((src[size] != c) && src[size])
++size;
*dst = (char *)malloc((size + 1) * sizeof(char));
if (*dst == NULL)
return (-1);
(*dst)[size] = '\0';
i = -1;
while (++i < size)
(*dst)[i] = src[i];
return (i);
}
char **ft_split(const char *s, char c)
{
char **strs;
int wcount;
int i;
int n;
int index;
if (s == NULL)
return (NULL);
wcount = words_counter(s, c);
strs = (char **)malloc((wcount + 1) * sizeof(*strs));
if (strs == NULL)
return (NULL);
strs[wcount] = NULL;
index = -1;
i = 0;
while (++index < wcount)
{
while (s[i] == c)
++i;
n = word_dup(s + i, &(strs[index]), c);
if (n < 0)
return (NULL);
i += n;
}
return (strs);
}