-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_strsplit.c
78 lines (71 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strsplit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dbrophy <dbrophy@student.42.us.org> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/02/19 12:54:04 by dbrophy #+# #+# */
/* Updated: 2020/02/19 12:54:04 by dbrophy ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#include "stdlib.h"
static int i_count_strings_and_clean(const char **s, char c)
{
int cnt;
const char *sr;
char last;
while (**s == c && **s != 0)
(*s)++;
sr = *s;
cnt = *sr != 0;
while (*sr)
{
last = *sr;
while (*sr == c)
sr++;
if (last == c && *sr != 0)
cnt++;
sr++;
}
return (cnt);
}
static char **i_split_loop(char **arr, const char *s, char c)
{
int i;
char last;
const char *so;
i = 0;
so = s;
last = *s;
while (*(++s))
{
if (*s == c && c != last)
arr[i++] = ft_strcut(so, c);
if (*s == c)
so = s + 1;
last = *s;
}
if (ft_strlen(so) > 0 && so[0] != c)
arr[i++] = ft_strcut(so, c);
arr[i] = NULL;
return (arr);
}
char **ft_strsplit(const char *s, char c)
{
int nstr;
char **arr;
if (s == NULL)
return (NULL);
nstr = i_count_strings_and_clean(&s, c);
arr = (char**)malloc(sizeof(char*) * (nstr + 1));
if (arr == NULL)
return (NULL);
if (nstr == 0)
{
arr[0] = NULL;
return (arr);
}
return (i_split_loop(arr, s, c));
}