-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_split.c
90 lines (82 loc) · 1.12 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
#include <stddef.h>
#include <stdlib.h>
#include "header/libft.h"
static void ft_clear(char **arr)
{
int i;
i = 0;
while (arr[i] != NULL)
{
free(arr[i]);
i++;
}
free(arr);
}
static int ft_count(const char *s, char c)
{
int n;
int i;
n = 0;
i = 0;
while (s[i] != '\0')
{
while (s[i] == c && s[i] != '\0')
{
i++;
}
if (s[i] != '\0')
n++;
while (s[i] != c && s[i] != '\0')
{
i++;
}
}
return (n);
}
static int ft_start(const char *s, char c, int i)
{
while (s[i] == c && s[i] != '\0')
{
i++;
}
return (i);
}
static int ft_end(const char *s, char c, int i)
{
while (s[i] == c && s[i] != '\0')
{
i++;
}
while (s[i] != c && s[i] != '\0')
{
i++;
}
return (i);
}
char **ft_split(const char *s, char c)
{
int i;
char **arr;
int j;
int k;
if (!s)
return (NULL);
i = 0;
j = 0;
arr = malloc((ft_count(s, c) + 1) * sizeof(char *));
if (!arr)
return (NULL);
while (s[i] != '\0')
{
k = ft_start(s, c, i);
if (s[k] == '\0')
break ;
i = ft_end(s, c, i);
arr[j] = ft_substr(s, k, (i - k));
if (!arr[j])
ft_clear(arr);
j++;
}
arr[j] = NULL;
return (arr);
}