-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
98 lines (90 loc) · 2.02 KB
/
ft_split.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/* ************************************************************************** */
/* */
/* :::::::: */
/* ft_split.c :+: :+: */
/* +:+ */
/* By: jvan-hal <[email protected]> +#+ */
/* +#+ */
/* Created: 2022/10/12 14:44:31 by jvan-hal #+# #+# */
/* Updated: 2023/03/23 11:57:47 by jvan-hal ######## odam.nl */
/* */
/* ************************************************************************** */
#include "libft.h"
#include <stdlib.h>
static int getarrlength(const char *s, char dlm)
{
int count;
char prevc;
count = 0;
prevc = dlm;
while (*s)
{
if (*s == dlm && prevc != dlm)
++count;
prevc = *s;
++s;
}
if (prevc != dlm)
++count;
return (count);
}
static char *getsplit(const char **s, char dlm)
{
int i;
char prevc;
char *split;
i = 0;
prevc = dlm;
while (i == 0 || s[0][i - 1])
{
if ((s[0][i] == dlm && prevc != dlm) || (!(s[0][i]) && prevc != dlm))
{
split = ft_substr(s[0], 0, i);
if (!split)
return (NULL);
s[0] += i;
return (split);
}
prevc = s[0][i];
++i;
}
return (NULL);
}
static void freearr(char **arr, int i)
{
--i;
while (i >= 0)
{
free(arr[i]);
arr[i] = NULL;
--i;
}
free(arr);
arr = NULL;
}
char **ft_split(char const *s, char c)
{
int arrsize;
int i;
char **arr;
if (!s)
return (NULL);
arrsize = getarrlength(s, c) + 1;
arr = ft_calloc(arrsize, sizeof(char *));
if (!arr)
return (NULL);
i = 0;
while (i < arrsize - 1)
{
while (*s == c)
++s;
arr[i] = getsplit(&s, c);
if (!arr[i])
{
freearr(arr, i);
return (NULL);
}
++i;
}
return (arr);
}