-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_split.c
113 lines (103 loc) · 2.22 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
104
105
106
107
108
109
110
111
112
113
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aizsak <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/11/07 11:44:15 by aizsak #+# #+# */
/* Updated: 2022/11/19 09:38:52 by aizsak ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int word_count(const char *str, char charset)
{
int i;
int count;
i = 0;
count = 1;
while (str[i] != '\0')
{
while (str[i] != '\0' && (str[i] == charset))
i++;
if (str[i] != '\0')
count++;
while (str[i] != '\0' && (str[i] != charset))
i++;
}
return (count);
}
static void free_all(char **tab, int i)
{
while (i > 0)
{
free(tab[i]);
i--;
}
free(tab);
return ;
}
static void attribute_word(const char *str, char set, char **tab, int l)
{
int i;
int j;
int len;
i = 0;
j = 0;
while (str[i] != '\0')
{
len = 0;
while (str[i] && str[i] == set)
i++;
while (str[i] && str[i] != set)
{
i++;
len++;
}
if (j < l)
{
tab[j] = malloc(sizeof(char) * (len + 1));
if (!(tab))
free_all(tab, j - 1);
j++;
}
}
}
static void word_write(const char *str, char set, char **tab, int l)
{
int i;
int j;
int k;
i = 0;
j = 0;
while (str[i] != '\0')
{
k = 0;
while (str[i] && str[i] == set)
i++;
while (str[i] && str[i] != set)
{
tab[j][k] = str[i];
k++;
i++;
}
if (j < l)
{
tab[j][k] = 0;
j++;
}
}
tab[j] = 0;
}
char **ft_split(char const *s, char c)
{
char **tab;
int len;
len = word_count(s, c);
tab = malloc(sizeof(char *) * len);
if (!tab)
return (NULL);
attribute_word(s, c, tab, len - 1);
word_write(s, c, tab, len - 1);
return (tab);
}