-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
65 lines (60 loc) · 1.61 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rabustam <rabustam@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/05/31 18:01:53 by rabustam #+# #+# */
/* Updated: 2023/04/20 15:19:53 by rabustam ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_count_strs(const char *s, char c)
{
int count;
int split;
size_t i;
i = 0;
count = 0;
split = 0;
while (s[i])
{
if (s[i] != c && split == 0)
{
split = 1;
count++;
}
else if (s[i] == c)
split = 0;
i++;
}
return (count);
}
char **ft_split(char const *s, char c)
{
char **strs;
size_t i;
size_t j;
int index;
strs = malloc((ft_count_strs(s, c) + 1) * sizeof(char *));
if (!strs)
return (NULL);
i = 0;
j = 0;
index = -1;
while (i <= ft_strlen(s))
{
if ((s[i] != c && s[i] != '\0') && index < 0)
index = i;
if ((s[i] == c || s[i] == '\0') && index >= 0)
{
strs[j] = ft_substr(s, index, (i - index));
j++;
index = -1;
}
i++;
}
strs[j] = NULL;
return (strs);
}