-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
96 lines (88 loc) · 1.39 KB
/
ft_split.c
File metadata and controls
96 lines (88 loc) · 1.39 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include "libft.h"
static size_t ft_count_word(char const *s, char c)
{
size_t i;
size_t count;
i = 0;
count = 0;
while (s[i] != '\0')
{
while (s[i] == c && s[i] != '\0')
i++;
if (s[i] != c)
count++;
while (s[i] != c && s[i] != '\0')
i++;
while (s[i] == c && s[i] != '\0')
i++;
}
return (count);
}
static char *ft_create_word(char const *s, char c)
{
char *word;
size_t i;
size_t len;
i = 0;
len = 0;
while (s[i] != '\0' && s[i] != c)
{
i++;
len++;
}
word = (char *)malloc((len + 1) * sizeof(char));
i = 0;
while (s[i] != '\0' && s[i] != c)
{
word[i] = s[i];
i++;
}
word[i] = '\0';
return (word);
}
static void ft_nfree(char **dst, size_t n)
{
while (n--)
free(dst[n]);
free(dst);
}
static int ft_create_array(char **dst, char const *s, char c)
{
size_t i;
size_t n;
i = 0;
n = 0;
while (s[i] != '\0')
{
if (s[i] != c)
{
dst[n] = ft_create_word(s, c);
if (!dst[n])
{
ft_nfree(dst, n);
return (-1);
}
n++;
}
while (s[i] != c && s[i] != '\0')
s++;
while (s[i] == c && s[i] != '\0')
s++;
}
dst[n] = NULL;
return (0);
}
char **ft_split(char const *s, char c)
{
char **dst;
size_t word_count;
if (!s)
return (0);
word_count = ft_count_word(s, c);
dst = (char **)malloc(sizeof(char *) * (word_count + 1));
if (dst == 0)
return (0);
if (ft_create_array(dst, s, c) == -1)
return (0);
return (dst);
}