-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
86 lines (77 loc) · 1.81 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ariahi <ariahi@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/17 06:27:52 by ariahi #+# #+# */
/* Updated: 2022/12/31 16:48:53 by ariahi ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int count_w(char const *s, char c)
{
int i;
i = 0;
while (*s && *s != c)
{
i++;
s++;
}
return (i);
}
static int count_s(char const *s, char c)
{
int i;
int count;
i = 0;
count = 0;
while (*s)
{
while (*s && *s == c)
s++;
i = count_w(s, c);
s += i;
if (i)
count++;
}
return (count);
}
static char *put_str(char const *s, int len)
{
char *str;
str = malloc(sizeof(char) * (len + 1));
if (!str)
return (0);
str[len] = 0;
while (len--)
str[len] = s[len];
return (str);
}
char **ft_split(char const *s, char c)
{
char **s_t;
int s_c;
int w_c;
int i;
i = -1;
if (!s)
return (0);
s_c = count_s(s, c);
s_t = (char **)malloc(sizeof(char *) * (s_c + 1));
if (!s_t)
return (0);
while (++i < s_c)
{
while (*s && *s == c)
s++;
w_c = count_w(s, c);
s_t[i] = put_str(s, w_c);
if (!(s_t[i]))
return (ft_free(s_t), NULL);
s += w_c;
}
s_t[s_c] = 0;
return (s_t);
}