-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_split.c
102 lines (92 loc) · 2.2 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
98
99
100
101
102
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rishimot <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/07/12 12:40:58 by rishimot #+# #+# */
/* Updated: 2020/07/17 15:53:43 by rishimot ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t ft_cnt_words(char const *s, char c)
{
size_t i;
size_t len;
i = 0;
len = 0;
while (s[i])
{
if (s[i] != c)
{
len++;
while (s[i] != c && s[i])
i++;
}
else
while (s[i] == c && s[i])
i++;
}
return (len);
}
static int skip_str(char const *s, char c, int index)
{
int len;
len = 0;
while (s[index + len] != c && s[index + len])
len++;
return (len);
}
static char **all_free(char ***p, int j)
{
while (j >= 0)
{
free((*p)[j]);
(*p)[j] = NULL;
j--;
}
free(*p);
*p = NULL;
return (0);
}
static char **ft_split_main(char const *s, char c)
{
size_t len;
char **p;
int now;
int j;
if (!(p = (char **)malloc(sizeof(char *) * (ft_cnt_words(s, c) + 1))))
return (0);
j = 0;
now = 0;
while (s[now])
{
while (s[now] == c && s[now])
now++;
if (!s[now])
break ;
len = skip_str(s, c, now);
if (!(p[j] = ft_substr(s, now, len)))
return (all_free(&p, j - 1));
j++;
now += len;
}
p[j] = NULL;
return (p);
}
char **ft_split(char const *s, char c)
{
char **p;
if (s == NULL)
return (0);
if (!c && !(*s))
{
if (!(p = (char **)malloc(sizeof(char *))))
return (0);
p[0] = NULL;
return (p);
}
p = ft_split_main(s, c);
return (p);
}