-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
110 lines (99 loc) · 2.11 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jonchoi <jonchoi@student.42seoul.kr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/07/12 07:24:34 by jonchoi #+# #+# */
/* Updated: 2022/07/16 07:15:16 by jonchoi ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
size_t ft_wordcnt(char const *s, char c)
{
size_t cnt;
size_t i;
cnt = 0;
i = 0;
while (s[i])
{
if (s[i] == c)
i++;
else
{
while (s[i] && s[i] != c)
i++;
cnt++;
}
}
return (cnt);
}
char *ft_strndup(const char *s, size_t n)
{
size_t i;
char *result;
i = 0;
result = (char *)malloc(sizeof(char) * (n + 1));
if (!result)
return (0);
while (i < n)
{
result[i] = s[i];
i++;
}
result[i] = '\0';
return (result);
}
int ft_free_malloc(char **result, size_t k)
{
size_t i;
i = 0;
while (i < k)
{
free(result[i]);
i++;
}
free(result);
return (0);
}
int ft_cutstr(char const *s, char c, char **result)
{
size_t i;
size_t j;
size_t k;
i = 0;
k = 0;
while (s[i])
{
if (s[i] == c)
i++;
else
{
j = 0;
while (s[i + j] != c && s[i + j])
j++;
result[k] = ft_strndup(&s[i], j);
if (!result[k])
return (ft_free_malloc(result, k));
i += j;
k++;
}
}
return (1);
}
char **ft_split(char const *s, char c)
{
size_t wordcnt;
char **result;
if (!s)
return (0);
wordcnt = ft_wordcnt(s, c);
result = (char **)malloc(sizeof(char *) * (wordcnt + 1));
if (!result)
return (0);
result[wordcnt] = 0;
if (!ft_cutstr(s, c, result))
return (0);
return (result);
}