-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathft_split.c
93 lines (85 loc) · 2.08 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: sel-mlil <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/10/26 20:35:11 by sel-mlil #+# #+# */
/* Updated: 2024/10/28 03:13:02 by sel-mlil ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int word_count(char *s, char sep)
{
int i;
int in_word;
int cp;
i = 0;
in_word = 0;
cp = 0;
while (s[i])
{
if (s[i] == sep)
{
in_word = 0;
}
else if (s[i] != sep && in_word == 0)
{
in_word = 1;
cp++;
}
i++;
}
return (cp);
}
static void *free_arr(char **arr, int i)
{
while (--i >= 0)
free(arr[i]);
free(arr);
return (NULL);
}
static char **filling_arr(char c, const char *s, char **arr, int words)
{
int i;
int start;
int end;
i = 0;
start = 0;
while (i < words)
{
while (s[start] && s[start] == c)
start++;
end = start;
while (s[end] && s[end] != c)
end++;
arr[i] = ft_substr(s, (unsigned int)start, (size_t)(end - start));
if (!arr[i])
return (free_arr(arr, i));
start = end + 1;
i++;
}
arr[i] = NULL;
return (arr);
}
char **ft_split(char const *s, char c)
{
int words;
char **splitted;
if (!s)
return (NULL);
if (!*s)
{
splitted = (char **)malloc(sizeof(char *));
if (!splitted)
return (NULL);
splitted[0] = NULL;
return (splitted);
}
words = word_count((char *)s, c);
splitted = (char **)malloc((words + 1) * sizeof(char *));
if (!splitted)
return (NULL);
return (filling_arr(c, s, splitted, words));
}