-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
102 lines (92 loc) · 2 KB
/
ft_split.c
File metadata and controls
102 lines (92 loc) · 2 KB
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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: belkarto <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/10/10 14:23:21 by belkarto #+# #+# */
/* Updated: 2022/10/24 05:03:21 by belkarto ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int alloc_count(const char *str, char c)
{
int i;
int counter;
counter = 0;
i = 0;
if (!str)
return (0);
while (str[i])
{
if (str[i] == c)
i++;
else
{
counter++;
while (str[i] != c && str[i])
i++;
}
}
return (counter);
}
static int string_alloc(const char *str, int c)
{
int i;
i = 0;
while (str[i] != c && str[i])
i++;
return (i);
}
static char **ft_free_str(char **str, int k)
{
int i;
i = 0;
while (i < k)
{
free(str[i]);
i++;
}
free(str);
return (0);
}
static int ft_fill_str(char *str, const char *s, int len)
{
int i;
i = 0;
while (i < len)
{
str[i] = s[i];
i++;
}
str[i] = 0;
return (i);
}
char **ft_split(char const *s, char c)
{
int i;
char **str;
int k;
int next;
str = (char **)ft_calloc((alloc_count(s, c) + 1), sizeof(char *));
if (!str || !s)
return (0);
k = 0;
i = 0;
while (s[i])
{
if (s[i] == c)
i++;
else
{
next = string_alloc(s + i, c);
str[k] = (char *)malloc((next + 1) * sizeof(char));
if (!str[k])
return (ft_free_str(str, k));
else
i += ft_fill_str(str[k++], s + i, next);
}
}
return (str);
}