-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_strsplit.c
executable file
·89 lines (79 loc) · 1.99 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
84
85
86
87
88
89
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strsplit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ngouy <ngouy@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2014/11/06 15:05:46 by ngouy #+# #+# */
/* Updated: 2015/11/04 17:25:01 by ngouy ### ########.fr */
/* */
/* ************************************************************************** */
/*
** Return a full memory allocated 2 size tab with part of s cutted by c.
*/
#include "libft.h"
static size_t ft_nbofwords(char const *s, char c)
{
int ret;
int i;
i = 0;
ret = i;
while (s[i])
{
if (s[i] && s[i] != c)
{
if (i == 0 || s[i - 1] == c)
ret++;
}
i++;
}
return (ret);
}
static size_t ft_wordsize(char const *s, int i, char c)
{
size_t ret;
ret = 0;
while (s[i] && s[i] != c)
{
i++;
ret++;
}
return (ret);
}
static char **ft_empt(void)
{
char **ret;
ret = (char **)malloc(sizeof(char *) * 1 + 1);
ret[0] = (char *)malloc(sizeof(char));
ret[0] = NULL;
ret[1] = NULL;
return (ret);
}
char **ft_strsplit(char const *s, char c)
{
char **ret;
int i;
int j;
size_t size_ret;
if (!s)
return (NULL);
i = 0;
j = i;
size_ret = ft_nbofwords(s, c);
if (size_ret == 0)
return (ft_empt());
ret = (char **)malloc(sizeof(char *) * size_ret + 1);
if (!ret)
return (NULL);
ret[size_ret] = NULL;
while (j < (int)size_ret)
{
while (s[i] == c)
i++;
ret[j] = ft_strsub(s, i, ft_wordsize(s, i, c));
i = i + ft_wordsize(s, i, c);
j++;
}
return (ret);
}