-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_split.c
74 lines (68 loc) · 1.75 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kpetrosy <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/01/27 19:43:46 by kpetrosy #+# #+# */
/* Updated: 2021/01/27 19:44:50 by kpetrosy ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
size_t get_cnt(char const *s, char c)
{
size_t cnt;
cnt = 0;
while (*s != '\0')
{
if (*s == c)
s++;
else
{
cnt++;
while (*s != '\0' && *s != c)
s++;
}
}
return (cnt);
}
char **free_machine(char **s, size_t idx)
{
while (s[idx] != NULL && idx >= 0)
{
free(s[idx]);
s[idx] = NULL;
idx--;
}
free(s);
s = NULL;
return (NULL);
}
char **ft_split(char const *s, char c)
{
size_t idx;
size_t len;
size_t word_cnt;
char **words;
if (!s || !(words = (char **)malloc(sizeof(char *) * (get_cnt(s, c) + 1))))
return (NULL);
word_cnt = get_cnt(s, c);
idx = 0;
while (*s)
{
if (*s == c)
s++;
else
{
len = 0;
while (*(s + len) && *(s + len) != c)
len++;
if (idx < word_cnt && !(words[idx++] = ft_substr(s, 0, len)))
return (free_machine(words, idx));
s += len;
}
}
words[idx] = 0;
return (words);
}