-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
90 lines (81 loc) · 1.9 KB
/
ft_split.c
File metadata and controls
90 lines (81 loc) · 1.9 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
/* ************************************************************************** */
/* */
/* :::::::: */
/* ft_split.c :+: :+: */
/* +:+ */
/* By: ivork <ivork@student.codam.nl> +#+ */
/* +#+ */
/* Created: 2020/11/08 21:11:29 by ivork #+# #+# */
/* Updated: 2021/12/17 13:49:31 by ivork ######## odam.nl */
/* */
/* ************************************************************************** */
#include "libft.h"
void ft_free_array(char **array, int x)
{
int i;
i = 0;
while (i < x)
{
free(array[i]);
i++;
}
free(array);
return ;
}
static size_t ft_count_words(char const *s, char c)
{
size_t i;
size_t words;
i = 0;
words = 0;
while (s[i] != '\0')
{
if (s[i] != c)
{
words++;
while (s[i] != c && s[i] != '\0')
i++;
}
else
i++;
}
return (words);
}
static char **ft_fill_in(char **array, const char *s, char c, int splits)
{
int i;
int j;
int k;
k = 0;
i = 0;
while (splits)
{
while (s[i] == c)
i++;
j = i;
while (s[i] != c && s[i] != '\0')
i++;
array[k] = ft_substr(s, j, (i - j));
if (array[k] == NULL)
{
ft_free_array(array, (k + 1));
return (NULL);
}
k++;
splits--;
}
return (array);
}
char **ft_split(char const *s, char c)
{
int words;
char **arr;
if (!s)
return (0);
words = ft_count_words(s, c);
arr = (char **)malloc(sizeof(char *) * (words + 1));
if (arr == NULL)
return (NULL);
arr[words] = NULL;
return (ft_fill_in(arr, s, c, words));
}