-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
108 lines (97 loc) · 2.05 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: azaher <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/01/07 15:32:15 by azaher #+# #+# */
/* Updated: 2023/01/11 14:56:38 by azaher ### ########.fr */
/* */
/* ************************************************************************** */
#include "so_long.h"
char *ft_strdup(const char *s1)
{
size_t i;
char *s2;
i = 0;
s2 = malloc((ft_strlen(s1) + 1) * sizeof(char));
if (!s2)
return (0);
if (s1 == 0)
return (0);
while (s1[i])
{
s2[i] = s1 [i];
i++;
}
s2[i] = '\0';
return (s2);
}
int ft_countwords(char *s, char c)
{
int i;
int count;
i = 0;
count = 0;
while (s[i])
{
while (s[i] == c && s[i])
i++;
if (s[i] != c && s[i])
count++;
while (s[i] != c && s[i])
i++;
}
return (count);
}
void ft_free(char **ret, int p)
{
int i;
i = 0;
while (i <= p)
{
free(ret[i]);
i++;
}
free (ret);
}
void ft_storewords(char **ret, char *s, char c)
{
int i;
int j;
int p;
i = 0;
j = 0;
p = 0;
while (s[i])
{
while (s[i] == c && s[i])
i++;
if (s[i] != c)
j = i;
while (s[i] != c && s[i])
i++;
if (i != j)
{
ret[p] = ft_substr(s, j, i - j);
if (!ret[p])
ft_free(ret, p);
p++;
}
}
}
char **ft_split(char const *s, char c)
{
int words;
char **ret;
if (s == NULL)
return (0);
words = ft_countwords((char *)s, c);
ret = malloc((words + 1) * sizeof(char *));
if (!ret)
return (NULL);
ft_storewords(ret, (char *)s, c);
ret[words] = NULL;
return (ret);
}