-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_strsplit.c
81 lines (73 loc) · 2.02 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: malexand <malexand@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/05/07 23:17:04 by alex #+# #+# */
/* Updated: 2017/02/16 17:34:27 by malexand ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static const char *ft_str_find_next(const char *str, char c, int skip)
{
if (skip)
while (*str != '\0' && *str == c)
str++;
else
while (*str != '\0' && *str != c)
str++;
return (str);
}
static int ft_str_count_splits(const char *str, char c)
{
int count;
count = 0;
while (*str != '\0')
{
str = ft_str_find_next(str, c, 1);
if (*str != '\0')
{
count++;
str = ft_str_find_next(str, c, 0);
}
}
return (count);
}
static char **ft_arraydel(char **ret, int len)
{
int count;
count = 0;
while (count < len)
free(ret[count]);
free(ret);
return (NULL);
}
char **ft_strsplit(char const *str, char c)
{
char **ret;
int count;
const char *next;
if (str == NULL)
return (NULL);
ret = (char**)malloc(sizeof(char*) * (ft_str_count_splits(str, c) + 1));
if (ret == NULL)
return (NULL);
count = 0;
while (*str != '\0')
{
str = ft_str_find_next(str, c, 1);
if (*str != '\0')
{
next = ft_str_find_next(str, c, 0);
ret[count] = ft_strsub(str, 0, next - str);
if (ret[count] == NULL)
return (ft_arraydel(ret, count));
count++;
str = next;
}
}
ret[count] = NULL;
return (ret);
}