-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_strsplit.c
78 lines (71 loc) · 1.86 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: imarakho <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/11/25 12:03:07 by imarakho #+# #+# */
/* Updated: 2016/12/01 20:52:10 by imarakho ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static char *wordscpy(char *ar, char const *str, char c, int index)
{
int start;
int end;
start = index;
while (str[start] != c)
start++;
end = start;
start = index;
ar = malloc(sizeof(char) * (end - start + 1));
index = 0;
while (start < end)
{
ar[index] = str[start];
start++;
index++;
}
ar[index] = '\0';
return (ar);
}
static int wordsnum(char const *str, char c)
{
int i;
int countwords;
i = 0;
countwords = 0;
while (str[i] != '\0')
{
if ((str[i] != c && str[i + 1] == c) ||
(str[i] != c && str[i + 1] == '\0'))
countwords++;
i++;
}
return (countwords);
}
char **ft_strsplit(char const *s, char c)
{
char **arr;
int i;
int j;
i = 0;
j = 0;
if (!s)
return (NULL);
arr = (char **)malloc(sizeof(char *) * (wordsnum(s, c) + 1));
if (!arr)
return (NULL);
while (j < wordsnum(s, c))
{
while (s[i] == c)
i++;
arr[j] = wordscpy(arr[j], s, c, i);
while (s[i] != c)
i++;
j++;
}
arr[j] = NULL;
return (arr);
}