-
Notifications
You must be signed in to change notification settings - Fork 2
/
ft_split.c
96 lines (86 loc) · 2.27 KB
/
ft_split.c
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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: adiaz-lo <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/01/13 11:12:22 by adiaz-lo #+# #+# */
/* Updated: 2020/01/14 08:36:58 by adiaz-lo ### ########.fr */
/* */
/* ************************************************************************** */
/*
** This function allocates (with malloc()) and returns an array of strings
** obtained by splitting 's' using the character 'c' as a delimiter. The array
** must be ended by a NULL pointer.
*/
#include "libft.h"
/*
** This auxiliar function
*/
static int ft_div_counter(char const *s, char c)
{
int i;
int counter;
counter = 0;
if (s[0] && s[0] != c)
counter++;
i = 0;
while (i < (int)ft_strlen(s))
{
if (s[i] == c && s[i + 1] != c && s[i + 1])
counter++;
i++;
}
return (counter);
}
/*
** This auxiliar function segments the 's' array into parts.
*/
static char *ft_segmentator(char const *s, char c, int i)
{
int j;
int k;
char *resultant_string;
j = i;
while (s[i] && s[i] != c)
i++;
resultant_string = (char *)malloc(sizeof(char) * ((i - j) + 1));
if (!resultant_string)
return (NULL);
k = 0;
while (j != i)
{
resultant_string[k] = s[j];
k++;
j++;
}
resultant_string[k] = '\0';
return (resultant_string);
}
char **ft_split(char const *s, char c)
{
char **array;
int i;
int j;
if (!s)
return (NULL);
array = (char **)malloc(sizeof(char *) * (ft_div_counter(s, c) + 1));
if (!array)
return (NULL);
i = 0;
j = 0;
while (i <= (int)ft_strlen(s) && ft_div_counter(s, c))
{
if (ft_strlen(ft_segmentator(s, c, i)))
{
array[j] = ft_segmentator(s, c, i);
i += (ft_strlen(array[j]) + 1);
j++;
}
else
i++;
}
array[j] = NULL;
return (array);
}