-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
97 lines (89 loc) · 2.17 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
88
89
90
91
92
93
94
95
96
97
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: abouramd <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/10/09 13:46:24 by abouramd #+# #+# */
/* Updated: 2022/10/19 11:59:38 by abouramd ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t char_count(char const *s, char c)
{
size_t index;
size_t count_t;
index = 0;
count_t = 0;
while (s[index] && s[index] == c)
index++;
while (s[index])
{
while (s[index] && s[index] != c)
index++;
while (s[index] && s[index] == c)
index++;
count_t++;
}
return (count_t);
}
static size_t new_i(char const *s, char c, size_t index)
{
while (s[index] && s[index] == c)
index++;
return (index);
}
static size_t splittostr(char const *s, char c, char **p)
{
size_t index;
size_t x;
size_t m;
size_t count_t;
index = 0;
count_t = 0;
index = new_i(s, c, index);
while (s[index])
{
m = 0;
x = index;
while (s[index] && s[index] != c)
index++;
p[count_t] = (char *)malloc(index - x + 1);
if (!p[count_t])
return (count_t);
while (x < index)
p[count_t][m++] = s[x++];
p[count_t][m] = '\0';
index = new_i(s, c, index);
count_t++;
}
return (count_t);
}
char **ft_split(char const *s, char c)
{
char **p;
size_t c_c;
size_t m;
if (!s)
return (NULL);
c_c = char_count(s, c);
p = (char **)malloc(sizeof(char *) * (c_c + 1));
if (!p)
return (NULL);
p[c_c] = NULL;
if (c_c == 0)
return (p);
m = splittostr(s, c, p);
if (m != c_c)
{
while (m > 0)
{
free (p[m - 1]);
m--;
}
free (p);
return (NULL);
}
return (p);
}