-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
99 lines (87 loc) · 2.38 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: younhwan <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/07/07 18:16:25 by younhwan #+# #+# */
/* Updated: 2022/07/14 15:32:10 by younhwan ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
char **ft_split(char const *s, char c);
static char *get_word(char const *s, char c, size_t *s_idx);
static size_t cnt_words(char const *s, char c);
static size_t cnt_word_len(char const *s, char c);
static char **force_quit(char **res);
char **ft_split(char const *s, char c)
{
char **res;
size_t words_len;
size_t words_idx;
size_t s_idx;
words_len = cnt_words(s, c);
res = (char **) malloc(sizeof(char *) * (words_len + 1));
if (!res || !s)
return (0);
words_idx = 0;
s_idx = 0;
while (s[s_idx] && words_idx < words_len)
{
while (s[s_idx] && s[s_idx] == c)
s_idx++;
if (s[s_idx])
res[words_idx++] = get_word(s, c, &s_idx);
if (!res[words_idx - 1])
return (force_quit(res));
}
res[words_idx] = 0;
return (res);
}
static char *get_word(char const *s, char c, size_t *s_idx)
{
char *res;
size_t word_len;
word_len = cnt_word_len(&s[*s_idx], c);
res = (char *) malloc(sizeof(char) * (word_len + 1));
if (!res)
return (0);
ft_strlcpy(res, &s[*s_idx], word_len + 1);
*s_idx += word_len;
return (res);
}
static size_t cnt_words(char const *s, char c)
{
size_t cnt;
size_t i;
cnt = 0;
i = 0;
while (s[i])
{
while (s[i] && s[i] == c)
i++;
if (s[i])
cnt++;
while (s[i] && s[i] != c)
i++;
}
return (cnt);
}
static size_t cnt_word_len(char const *s, char c)
{
size_t len;
len = 0;
while (s[len] && s[len] != c)
len++;
return (len);
}
static char **force_quit(char **res)
{
size_t i;
i = 0;
while (res[i])
free(res[i++]);
free(res);
return (0);
}