-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
110 lines (99 loc) · 2.2 KB
/
ft_split.c
File metadata and controls
110 lines (99 loc) · 2.2 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kmoutaou <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/14 22:41:21 by kmoutaou #+# #+# */
/* Updated: 2021/11/19 16:35:29 by kmoutaou ### ########.fr */
/* */
/* ************************************************************************** */
/*
ft_split is a function that allocates and returns an array of strings
obtained by splitting s using the c delimiter.
*/
#include "libft.h"
static int ft_wordcount(const char *s, char c)
{
int i;
int l;
i = 0;
l = 0;
while (s[i])
{
while (s[i] && s[i] == c)
i++;
if (s[i] && s[i] != c)
l++;
while (s[i] && s[i] != c)
i++;
}
return (l);
}
static int ft_wordlen(const char *s, char c)
{
int l;
int i;
i = 0;
l = 0;
while (s[i] && s[i] != c)
{
l++;
i++;
}
return (l);
}
static char *ft_popup(const char *s, char c)
{
int i;
int length;
char *new_s;
i = 0;
length = ft_wordlen(s, c);
new_s = (char *)malloc(sizeof(char) * length + 1);
if (!new_s)
return (new_s);
while (s[i] && s[i] != c)
{
new_s[i] = s[i];
i++;
}
new_s[i] = '\0';
return (new_s);
}
static char **ft_dmagic(char const *s, char **str, char c, int j)
{
while (*s)
{
while (*s && *s == c)
s++;
if (*s && *s != c)
{
str[j] = ft_popup(s, c);
if (!str[j])
{
free(str);
return (NULL);
}
j++;
}
while (*s && *s != c)
s++;
}
str[j] = 0;
return (str);
}
char **ft_split(char const *s, char c)
{
char **str;
int j;
j = 0;
if (!s)
return (0);
str = (char **)malloc(sizeof(char *) * (ft_wordcount(s, c) + 1));
if (!str)
return (str);
str = ft_dmagic(s, str, c, j);
return (str);
}