Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
yabtaour
GitHub Repository: yabtaour/Philosophers-42
Path: blob/master/philo_bonus/ft_split_bonus.c
882 views
1
/* ************************************************************************** */
2
/* */
3
/* ::: :::::::: */
4
/* ft_split_bonus.c :+: :+: :+: */
5
/* +:+ +:+ +:+ */
6
/* By: yabtaour <[email protected]> +#+ +:+ +#+ */
7
/* +#+#+#+#+#+ +#+ */
8
/* Created: 2022/05/23 00:07:22 by yabtaour #+# #+# */
9
/* Updated: 2022/05/23 00:07:24 by yabtaour ### ########.fr */
10
/* */
11
/* ************************************************************************** */
12
#include "philosophers_bonus.h"
13
14
static size_t word_count(const char *s, char c)
15
{
16
int i;
17
int count;
18
19
i = 0;
20
count = 0;
21
while (s[i] != '\0')
22
{
23
while (s[i] != '\0' && s[i] == c)
24
i++;
25
if (s[i] != '\0')
26
{
27
if ((s[i - 1] == c || i == 0))
28
count++;
29
i++;
30
}
31
}
32
return (count);
33
}
34
35
static char **ft_free_tab(char **str, int i)
36
{
37
while (i >= 0)
38
{
39
free(str[i]);
40
i--;
41
}
42
free(str);
43
return (str);
44
}
45
46
void free_split(char **arguments)
47
{
48
int i;
49
50
i = 0;
51
while (arguments[i])
52
{
53
free(arguments[i]);
54
i++;
55
}
56
free(arguments);
57
}
58
59
static char **ft_allocation(char const *s, char c)
60
{
61
char **ptr;
62
63
if (s == NULL)
64
return (NULL);
65
ptr = ft_calloc((word_count(s, c) + 1), sizeof(char *));
66
return (ptr);
67
}
68
69
char **ft_split(char *s, char c)
70
{
71
char **ptr;
72
int j;
73
int i;
74
75
ptr = ft_allocation(s, c);
76
if (!ptr)
77
return (ptr);
78
i = 0;
79
while (*s)
80
{
81
while (*s && *s == c)
82
s++;
83
j = 0;
84
while (s[j] != '\0' && s[j] != c)
85
j++;
86
if (j != 0)
87
{
88
ptr[i] = ft_substr(s, 0, j);
89
if (ptr[i] == NULL)
90
return (ft_free_tab(ptr, i));
91
i++;
92
}
93
s = s + j;
94
}
95
return (ptr);
96
}
97
98