-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_strsplit.c
83 lines (74 loc) · 1.89 KB
/
ft_strsplit.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strsplit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ylagtab <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/04/03 04:47:19 by ylagtab #+# #+# */
/* Updated: 2021/01/15 19:17:04 by ylagtab ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int count_words(char *s, char c)
{
int i;
int k;
int count;
i = 0;
count = 0;
while (s[i] != '\0')
{
while (s[i] && s[i] == c)
i++;
k = i;
while (s[i] && s[i] != c)
i++;
if (k != i)
count++;
}
return (count);
}
static char **create_table(const char *s, char c)
{
char **t;
int w_count;
w_count = count_words((char *)s, c) + 1;
t = (char **)ft_malloc(w_count * sizeof(char *));
return (t);
}
static char **free_table(char **words, int size)
{
int i;
i = 0;
while (i < size)
{
free(words[i]);
i++;
}
free(words);
return (NULL);
}
char **ft_strsplit(char const *s, char c)
{
int i;
int j;
int start;
char **words;
if (s == NULL || (words = create_table(s, c)) == NULL)
return (NULL);
i = 0;
j = 0;
while (s[i] != '\0')
{
while (s[i] && s[i] == c)
i++;
start = i;
while (s[i] && s[i] != c)
i++;
if (start != i && (words[j++] = ft_strsub(s, start, i - start)) == NULL)
return (free_table(words, j));
}
words[j] = NULL;
return (words);
}