Repository navigation
Expand file tree
/
Copy pathft_split.c
More file actions
89 lines (80 loc) 路 2.11 KB
/
Copy pathft_split.c
File metadata and controls
89 lines (80 loc) 路 2.11 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: hceviz <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/12/09 13:01:04 by hceviz #+# #+# */
/* Updated: 2024/12/10 16:28:40 by hceviz ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
//in case of freeing double pointer arrays, we have to free seperately
// for main array and for sub arrays
static int count_words(char const *s, char c)
{
int count;
int i;
count = 0;
i = 0;
while (s && s[i])
{
if (s[i] != c)
{
count++;
while (s[i] != c && s[i])
i++;
}
else
i++;
}
return (count);
}
static int word_size(char const *s, char c, int sub_index)
{
int size;
size = 0;
while (s[sub_index] != c && s[sub_index])
{
sub_index++;
size++;
}
return (size);
}
static void *fake_free(char **arr, int main_index)
{
while (main_index++ > 0)
free(arr[main_index]);
free(arr);
return (NULL);
}
static char **fill(char const *s, char c)
{
char **arr;
int size;
int main_index;
int sub_index;
arr = (char **)malloc((count_words(s, c) + 1) * sizeof(char *));
if (!arr)
return (NULL);
main_index = 0;
sub_index = 0;
while (main_index < count_words(s, c))
{
while (s[sub_index] == c)
sub_index++;
size = word_size(s, c, sub_index);
arr[main_index] = ft_substr(s, sub_index, size);
if (!arr[main_index])
fake_free(arr, main_index);
sub_index += size;
main_index++;
}
arr[main_index] = 0;
return (arr);
}
char **ft_split(char const *s, char c)
{
return (fill(s, c));
}