-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
104 lines (95 loc) · 2.22 KB
/
ft_split.c
File metadata and controls
104 lines (95 loc) · 2.22 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: manmoral <manmoral@student.42malaga.com +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2026/04/28 11:29:06 by manmoral #+# #+# */
/* Updated: 2026/05/06 15:26:59 by manmoral ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static char **wordcount(char const *s, char c);
static char **freemalloc(char **str, int n);
static int wordlen(const char *str, char c, int start);
char **ft_split(char const *s, char c);
/*int main(int argc, char **argv)
{
int i = 0;
char **result;
if (argc != 2)
{
result = ft_split(argv[1], argv[2][0]);
while (result[i] != NULL)
{
printf("%s\n", result[i]);
i++;
}
}
return (0);
}*/
static char **wordcount(char const *s, char c)
{
int i;
int j;
char **str;
i = 0;
j = 0;
while (s[i])
{
if (s[i] != c && (i == 0 || s[i - 1] == c))
j++;
i++;
}
str = malloc(sizeof(char *) * (j + 1));
if (!str)
return (NULL);
return (str);
}
static char **freemalloc(char **str, int n)
{
if (!str[n])
{
while (--n)
{
free(str[n]);
}
free(str);
}
return (0);
}
static int wordlen(const char *str, char c, int start)
{
int i;
i = start;
while (str[i] && str[i] != c)
i++;
return (i - start);
}
char **ft_split(char const *s, char c)
{
char **result;
int n;
int i;
int start;
int len;
if (!s)
return (NULL);
result = wordcount(s, c);
n = -1;
i = -1;
while (s[++i])
{
if (s[i] != c && (i == 0 || s[i - 1] == c))
{
start = i;
len = wordlen(s, c, i);
result[++n] = ft_substr(s, start, len);
if (!result[n])
freemalloc(result, n);
}
}
result[++n] = 0;
return (result);
}