-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_split.c
78 lines (71 loc) · 1.82 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: muraler <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/02/10 16:50:15 by muraler #+# #+# */
/* Updated: 2022/02/10 16:50:33 by muraler ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int wordcounter(const char *p, char c)
{
int i;
int trigger;
i = 0;
trigger = 0;
while (*p)
{
if (*p != c && trigger == 0)
{
trigger = 1;
i++;
}
else if (*p == c)
trigger = 0;
p++;
}
return (i);
}
static char *worddup(const char *s, int start, int end)
{
int i;
char *word;
i = 0;
word = malloc(sizeof(char) * (end - start + 1));
if (!word)
return (NULL);
while (start < end)
word[i++] = s[start++];
word[i] = '\0';
return (word);
}
char **ft_split(char const *s, char c)
{
char **split;
size_t i;
int a;
int start;
if (!s)
return (0);
i = -1;
a = 0;
start = -1;
split = malloc(sizeof(char *) * (wordcounter(s, c) + 1));
if (!split)
return (0);
while (++i <= ft_strlen(s))
{
if (s[i] != c && start < 0)
start = i;
else if ((s[i] == c || i == ft_strlen(s)) && start >= 0)
{
split[a++] = worddup(s, start, i);
start = -1;
}
}
split[a] = NULL;
return (split);
}