-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_strsplit.c
More file actions
110 lines (99 loc) · 2.17 KB
/
Copy pathft_strsplit.c
File metadata and controls
110 lines (99 loc) · 2.17 KB
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
/* ************************************************************************** */
/* */
/* :::::::: */
/* ft_strsplit.c :+: :+: */
/* +:+ */
/* By: eovertoo <marvin@codam.nl> +#+ */
/* +#+ */
/* Created: 2019/04/03 22:22:45 by eovertoo #+# #+# */
/* Updated: 2019/04/10 20:49:37 by eovertoo ######## odam.nl */
/* */
/* ************************************************************************** */
#include "libft.h"
static int count_word(char const *s, char c)
{
int i;
int cnt;
i = 0;
cnt = 0;
while (s[i] != '\0')
{
if (s[i] == c && s[i + 1] != c && s[i + 1] != '\0')
cnt++;
i++;
}
if (s[0] != '\0' && s[0] != c)
cnt++;
return (cnt);
}
static void make_free(char **d)
{
int i;
i = 0;
while (d[i] != NULL)
{
free(d[i]);
i++;
}
free(d);
}
static char *ft_make_space(char **d, int i)
{
char *x;
x = (char*)malloc(sizeof(char) * (i + 1));
if (!x)
{
make_free(d);
return (NULL);
}
return (x);
}
static char *put_word(const char *s, char c, int *i, char **d)
{
int k;
int l;
char *ret;
int j;
j = 0;
k = *i;
l = *i;
while (s[k] != c && s[k] != '\0')
k++;
ret = ft_make_space(d, (k - l));
if (ret == NULL)
return (NULL);
while (j < (k - l))
{
ret[j] = s[*i];
j++;
*i = *i + 1;
}
ret[j] = '\0';
while (s[*i] == c)
*i = *i + 1;
return (ret);
}
char **ft_strsplit(char const *s, char c)
{
int i;
char **d;
int k;
int words;
if (!s)
return (NULL);
words = count_word(s, c);
i = 0;
k = 0;
d = (char**)malloc(sizeof(char*) * (words + 1));
if (!d)
return (NULL);
while (s[i] == c)
i++;
while (k < words && s[i] != '\0')
{
d[k] = put_word(s, c, &i, d);
k++;
}
d[k] = NULL;
return (d);
}