-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_strsplit.c
73 lines (66 loc) · 1.76 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strsplit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: apoisson <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/11/16 14:45:38 by apoisson #+# #+# */
/* Updated: 2018/03/14 01:44:55 by abassibe ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_count_word(const char *s, char c)
{
int i;
int word;
i = 0;
word = 0;
while (s[i] != '\0')
{
if (s[i] != c && s[i + 1] == c)
word++;
if (s[i] != c && s[i + 1] == '\0')
word++;
i++;
}
return (word);
}
static char *ft_add_word_tab(const char *s, char c, int *i)
{
int j;
char *str;
char *tmp;
j = *i;
while (s[*i] && s[*i] != c)
*i = *i + 1;
tmp = ft_strsub(s, j, *i - j);
str = ft_strdup(tmp);
ft_strdel(&tmp);
while (s[*i] == c)
*i = *i + 1;
return (str);
}
char **ft_strsplit(char const *s, char c)
{
int i;
int j;
int word;
char **tab;
i = 0;
j = 0;
if (!s || !c)
return (NULL);
word = ft_count_word(s, c);
if (!(tab = (char**)malloc(sizeof(tab) * (word + 1))))
return (NULL);
while (s[i] == c)
i++;
while (j < word && s[i])
{
tab[j] = ft_add_word_tab(s, c, &i);
j++;
}
tab[j] = 0;
return (tab);
}