-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
123 lines (111 loc) · 2.33 KB
/
ft_split.c
File metadata and controls
123 lines (111 loc) · 2.33 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mobouifr <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/11/24 09:50:39 by mobouifr #+# #+# */
/* Updated: 2023/12/10 11:27:00 by mobouifr ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int wrdcount(char const *str, char c)
{
int i;
int count;
i = 0;
count = 0;
while (str && str[i] != '\0')
{
if (str[i] != c)
{
count++;
while (str[i] != '\0' && str[i] != c)
i++;
}
else if (str[i] == c)
i++;
}
return (count);
}
static size_t wrdlen(char const *s, char c)
{
size_t i;
i = 0;
while (s[i] != '\0' && s[i] != c)
{
i++;
}
return (i);
}
static char **ft_free(char **ptr, size_t j)
{
while (j > 0)
{
free(ptr[j - 1]);
j--;
}
free(ptr);
return (NULL);
}
static char *help(char const *s, char c)
{
size_t i;
char *ptr;
i = 0;
ptr = (char *)malloc(wrdlen(s, c) + 1);
if (!ptr)
return (NULL);
while (s[i] != '\0' && s[i] != c)
{
ptr[i] = s[i];
i++;
}
ptr[i] = '\0';
return (ptr);
}
char **ft_split(char const *s, char c)
{
char **ptr;
size_t i;
if (!s)
return (NULL);
ptr = (char **)malloc((wrdcount(s, c) + 1) * sizeof(char *));
if (!ptr)
return (NULL);
i = 0;
while (*s != '\0')
{
while (*s == c)
s++;
if (*s != '\0')
{
ptr[i] = help(s, c);
if (ptr[i] == NULL)
return (ft_free(ptr, i));
i++;
}
while (*s != '\0' && *s != c)
s++;
}
ptr[i] = NULL;
return (ptr);
}
/*
int main(void)
{
char const *input_string;
char **result;
int i;
input_string = "lkhdra";
result = ft_split(input_string, NULL);
i = 0;
while (result[i])
{
printf("%s\n", result[i]);
i++;
}
system("leaks a.out");
return (0);
}*/