-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_strsplit.c
84 lines (75 loc) · 1.88 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strsplit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: sgrindhe <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/08/04 23:27:15 by sgrindhe #+# #+# */
/* Updated: 2018/08/12 01:40:52 by sgrindhe ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_count_word(char const *s, char c)
{
unsigned int i;
int counter;
i = 0;
counter = 0;
while (s[i])
{
while (s[i] == c)
i++;
if (s[i] != '\0')
counter++;
while (s[i] && (s[i] != c))
i++;
}
return (counter);
}
static char **prelim_checks(char const *s, char c)
{
char **tab;
if (!s)
return (NULL);
tab = (char **)malloc(sizeof(char *) * (ft_count_word(s, c) + 1));
if (tab == NULL)
return (NULL);
return (tab);
}
static char *ft_strndup(const char *s, size_t n)
{
char *str;
str = ft_strnew(n);
if (str == NULL)
return (NULL);
str = ft_strncpy(str, s, n);
str[n] = '\0';
return (str);
}
char **ft_strsplit(char const *s, char c)
{
int i;
int j;
int k;
char **tab;
i = 0;
k = 0;
if (!(tab = prelim_checks(s, c)))
return (NULL);
while (s[i])
{
while (s[i] == c)
i++;
j = i;
while (s[i] && s[i] != c)
i++;
if (i > j)
{
tab[k] = ft_strndup(s + j, i - j);
k++;
}
}
tab[k] = NULL;
return (tab);
}