-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_split.c
87 lines (79 loc) · 1.89 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: abkssiba <abkssiba@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/10/22 13:03:04 by abkssiba #+# #+# */
/* Updated: 2021/05/24 15:57:37 by abkssiba ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static char **ft_get_arr(char const *str, char c)
{
char **arr;
int count;
int i;
int j;
i = 0;
count = 0;
while (str[i])
{
j = i;
while (str[j] != c && str[j] != '\0')
j++;
if (j > i)
{
count++;
i = j;
continue ;
}
i++;
}
arr = (char **)malloc((count + 1) * sizeof(char *));
return (arr);
}
static char **ft_free(char **str, int count)
{
int i;
i = 0;
while (i < count + 1)
{
free(str[i++]);
}
free(str);
return (NULL);
}
static void init_vars(int *i, int *count)
{
*count = 0;
*i = -1;
}
char **ft_split(char const *s, char c)
{
char **str;
int count;
int i;
int j;
str = ft_get_arr(s, c);
if (!s || !str)
return (NULL);
init_vars(&i, &count);
while (s[++i] != '\0')
{
j = i;
while (s[j] != c && s[j] != '\0')
j++;
if (j > i)
{
str[count] = (char *)malloc(sizeof(char) * (j - i + 1));
if (!str[count])
return (ft_free(str, count));
ft_strlcpy(str[count++], s + i, j - i + 1);
i = j - 1;
}
}
str[count] = 0;
return (str);
}