-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
97 lines (86 loc) · 1.93 KB
/
Copy pathft_split.c
File metadata and controls
97 lines (86 loc) · 1.93 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tunglaub <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/04/21 12:33:26 by tunglaub #+# #+# */
/* Updated: 2024/04/21 12:33:31 by tunglaub ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int count_words(const char *s, char c)
{
int count;
int i;
i = 0;
count = 0;
while (s[i])
{
if (s[i] != c)
{
count++;
while (s[i] && s[i] != c)
i++;
}
else
i++;
}
return (count);
}
static char **memory_allocation(char const *s, char c)
{
char **ptr;
ptr = malloc(sizeof(char *) * (count_words(s, c) + 1));
if (!ptr)
return (NULL);
return (ptr);
}
static void ft_free(char **ptr)
{
int i;
i = 0;
while (ptr[i])
{
free(ptr[i]);
i++;
}
free(ptr);
}
static char **find(char **ptr, char const *s, char c)
{
int i;
int j;
int start;
i = 0;
j = 0;
while (i < count_words(s, c))
{
while (s[j] == c)
j++;
start = j;
while (s[j] && s[j] != c)
j++;
ptr[i] = ft_substr(s, start, (j - start));
if (!ptr[i])
{
ft_free(ptr);
return (NULL);
}
i++;
}
ptr[count_words(s, c)] = NULL;
return (ptr);
}
char **ft_split(char const *s, char c)
{
char **ptr;
if (!s)
return (NULL);
ptr = memory_allocation(s, c);
if (!ptr)
return (NULL);
ptr = find(ptr, s, c);
return (ptr);
}