-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_strsplit.c
68 lines (61 loc) · 1.77 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strsplit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: yochered <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/10/27 15:14:46 by yochered #+# #+# */
/* Updated: 2018/10/27 15:14:51 by yochered ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
#include <libft.h>
static int count_words(char const *s, char c)
{
int words;
int len;
int i;
words = 0;
i = -1;
len = ft_strlen(s);
while (++i < len)
{
if (s[i] != c && (s[i + 1] == c || s[i + 1] == '\0'))
words++;
}
return (words);
}
static int count_len(char const *s, char c)
{
int len;
len = 0;
while (*s == c)
s++;
while (s[len] != c && s[len] != '\0')
len++;
return (len);
}
char **ft_strsplit(char const *s, char c)
{
int i;
int j;
int k;
char **res;
if (!s || !(res = (char **)malloc(sizeof(*res) * (count_words(s, c) + 1))))
return (NULL);
i = -1;
j = 0;
while (++i < count_words(s, c))
{
k = 0;
if (!(res[i] = ft_strnew(count_len(&s[j], c))))
res[i] = NULL;
while (s[j] == c)
j++;
while (s[j] != c && s[j])
res[i][k++] = s[j++];
}
res[i] = 0;
return (res);
}