-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
82 lines (74 loc) · 1.82 KB
/
ft_split.c
File metadata and controls
82 lines (74 loc) · 1.82 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: salecler <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/06/24 17:29:45 by salecler #+# #+# */
/* Updated: 2022/06/29 23:44:29 by salecler ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_len_w(char const *s, char c)
{
int n;
n = 0;
while (s[n] != c && s[n] != '\0')
n++;
return (n);
}
static int ft_nbr_w(char const *s, char c)
{
int i;
int n;
i = 0;
n = 0;
while (s[i] != '\0')
{
while (s[i] == c)
i++;
if (s[i] != c && s[i] != '\0')
n++;
while (s[i] != c && s[i] != '\0')
i++;
}
return (n);
}
static char **ft_free_w(char **w, int pos_w)
{
while (pos_w >= 0)
{
free(w[pos_w]);
pos_w--;
}
free(w);
return (NULL);
}
char **ft_split(char const *s, char c)
{
char **w;
int nbr_w;
int pos_w;
int n;
if (!s)
return (NULL);
nbr_w = ft_nbr_w(s, c);
w = (char **)malloc(sizeof(char *) * (nbr_w + 1));
if (!w)
return (NULL);
w[nbr_w] = NULL;
pos_w = 0;
n = 0;
while (pos_w < nbr_w)
{
while (s[n] == c)
n++;
w[pos_w] = ft_substr(s, n, ft_len_w(s + n, c));
if (!w[pos_w])
return (ft_free_w(w, pos_w));
n += ft_len_w(s + n, c);
pos_w++;
}
return (w);
}