-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_strsplit.c
81 lines (74 loc) · 1.83 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strsplit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mrychkov <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/04/29 20:43:49 by mrychkov #+# #+# */
/* Updated: 2018/02/16 16:39:19 by mrychkov ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t ft_tabsize(char const *s, char c)
{
size_t i;
size_t word_count;
size_t j;
i = 0;
word_count = 0;
while (s[i])
{
j = 0;
while (s[i] == c && s[i])
i++;
while (s[i] != c && s[i])
{
i++;
j++;
}
if (j)
word_count++;
}
return (word_count);
}
static char **ft_split(char **tab, char c, char const *s)
{
size_t word;
size_t i;
size_t j;
i = 0;
word = 0;
while (s[i])
{
j = 0;
while (s[i] == c && s[i])
i++;
while (s[i + j] != c && s[i + j])
j++;
if (j)
{
if (!(tab[word] = ft_strsub(s, i, j)))
{
ft_memdel((void **)tab);
return (NULL);
}
i = i + j;
word++;
}
}
return (tab);
}
char **ft_strsplit(char const *s, char c)
{
char **tab;
size_t word_count;
if (!s)
return (NULL);
word_count = ft_tabsize(s, c);
if (!(tab = (char **)ft_memalloc(sizeof(*tab) * (word_count + 1))))
return (NULL);
ft_split(tab, c, s);
tab[word_count] = NULL;
return (tab);
}