-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathft_strsplit.c
60 lines (55 loc) · 1.71 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strsplit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: smbaabu <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/02/23 15:20:02 by smbaabu #+# #+# */
/* Updated: 2019/02/28 17:32:59 by smbaabu ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t ft_strdelcnt(const char *s, char c)
{
size_t count;
size_t i;
count = 0;
i = 0;
while (s[i])
{
if (s[i] == c && (i > 0 && s[i - 1] != c))
count++;
if (!s[i + 1] && s[i] != c)
count++;
i++;
}
return (count);
}
char **ft_strsplit(char const *s, char c)
{
size_t i;
size_t start;
size_t idx;
int count;
char **ret;
if (!s || !c)
return (NULL);
count = ft_strdelcnt(s, c);
if ((ret = (char **)ft_memalloc(sizeof(char *) * count + 1)) == NULL)
return (NULL);
i = 0;
idx = 0;
while (s[i])
{
if (s[i] != c && (i == 0 || (i > 0 && s[i - 1] == c)))
start = i;
if (i > 0 && s[i] == c && s[i - 1] != c)
ret[idx++] = ft_strsub(s, start, i - start);
if (i > 0 && !s[i + 1] && s[i] != c)
ret[idx++] = ft_strsub(s, start, i - start + 1);
i++;
}
ret[idx] = NULL;
return (ret);
}