-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
125 lines (114 loc) · 2.25 KB
/
ft_split.c
File metadata and controls
125 lines (114 loc) · 2.25 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
124
125
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: hlehmann <hlehmann@student.42wolfsburg.de> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/05/13 16:54:48 by hlehmann #+# #+# */
/* Updated: 2021/05/13 16:57:26 by hlehmann ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_words(char const *s, char c)
{
int i;
int words;
i = 0;
words = 0;
while (s[i] && s[i] == c)
i++;
while (s[i])
{
words++;
while (s[i] && s[i] != c)
i++;
while (s[i] && s[i] == c)
i++;
}
return (words);
}
static int ft_length(char const *s, char c, int a)
{
int i;
int len;
i = 0;
len = 0;
while (s[i] && s[i] == c)
i++;
while (a)
{
if (s[i] == c && s[i + 1] != c)
a--;
i++;
}
while (s[i] && s[i] != c)
{
len++;
i++;
}
return (len);
}
static char *ft_copy(char const *s, char c, int a)
{
char *word;
int i;
int j;
i = 0;
j = 0;
word = (char *)malloc(sizeof(char) * ft_length(s, c, a) + 1);
if (!word)
return (NULL);
while (s[i] && s[i] == c)
i++;
while (a)
{
if (s[i] == c && s[i + 1] != c)
a--;
i++;
}
while (s[i] && s[i] != c)
{
word[j] = s[i];
j++;
i++;
}
word[j] = 0;
return (word);
}
static void ft_free_dest(char **dest)
{
int i;
i = 0;
while (dest[i])
{
free(dest[i]);
i++;
}
}
char **ft_split(char const *s, char c)
{
char **dest;
int words;
int i;
if (!s)
return (NULL);
words = ft_words(s, c);
dest = (char **)malloc(sizeof(char *) * (words + 1));
if (!dest)
return (NULL);
i = 0;
while (i < words)
{
dest[i] = ft_copy(s, c, i);
if (!dest[i])
{
ft_free_dest(dest);
free(dest);
return (NULL);
}
i++;
}
dest[i] = NULL;
return (dest);
}