-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
103 lines (94 loc) · 2.24 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
103
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jode-vri <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/11/15 12:13:30 by jode-vri #+# #+# */
/* Updated: 2020/11/15 12:27:03 by jode-vri ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
#include <stdio.h>
static void ft_free(char **dest, int count)
{
while (count >= 0)
{
free(dest[count]);
dest[count] = 0;
count--;
}
free(dest);
dest = 0;
}
static int word_size(char *s, char c, int i)
{
int j;
j = 0;
while (s[i + j] != 0 && s[i + j] != c)
j++;
return (j);
}
static char **malloc_word(char *s, char c, char **dest, int *i)
{
while (s[i[0]] && ++i[2] >= -5)
{
while (s[i[0]] == c && s[i[0]] != 0)
i[0]++;
if (s[i[0]] == 0)
dest[i[2]] = 0;
if (s[i[0]] == 0)
return (dest);
if (!(dest[i[2]] =
malloc((word_size(s, c, i[0]) + 1) * sizeof(char))))
{
ft_free(dest, i[2]);
return (0);
}
i[1] = 0;
while (s[i[0]] != c && s[i[0]] != 0)
{
dest[i[2]][i[1]] = s[i[0]];
i[0]++;
i[1]++;
}
dest[i[2]][i[1]] = 0;
}
dest[i[2] + 1] = 0;
return (dest);
}
static int count_words(char *s, char c)
{
int i;
int count;
i = 0;
count = 0;
while (s[i])
{
while (s[i] == c)
i++;
if (s[i] == '\0')
return (count);
count++;
while (s[i] != c && s[i] != 0)
i++;
}
return (count);
}
char **ft_split(char const *s, char c)
{
char **dest;
int w_count;
int i[3];
i[0] = 0;
i[1] = -1;
if (!s)
return (0);
w_count = count_words((char *)s, c);
i[2] = -1;
if (!(dest = malloc((w_count + 1) * sizeof(char *))))
return (0);
dest = malloc_word((char *)s, c, dest, i);
return (dest);
}