-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
106 lines (97 loc) · 2.63 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
97
98
99
100
101
102
103
104
105
106
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mmalie <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/11/07 09:57:39 by mmalie #+# #+# */
/* Updated: 2024/11/14 09:32:03 by mmalie ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
/*
* Splits a string into a memory allocated array of substrings,
* separated by a specified delimiter.
*/
char **ft_split(char const *s, char c);
static int count_tokens(char const *s, char delim);
static char **store_tokens(char const *s, char delim, char **array);
static char **malloc_storage(char **array, int i, int token_len);
char **ft_split(char const *s, char c)
{
char **array;
int nb_tokens;
array = NULL;
nb_tokens = count_tokens(s, c);
array = (char **)malloc((nb_tokens + 1) * sizeof(char *));
if (array == NULL)
return (NULL);
array = store_tokens(s, c, array);
if (array == NULL)
return (NULL);
return (array);
}
static int count_tokens(char const *s, char delim)
{
int nb_tokens;
int i;
nb_tokens = 0;
i = 0;
while (s[i] != '\0')
{
while (s[i] == delim && s[i] != '\0')
i++;
if (s[i] != delim && s[i] != '\0')
{
nb_tokens++;
while (s[i] != delim && s[i] != '\0')
i++;
}
}
return (nb_tokens);
}
static char **store_tokens(char const *s, char delim, char **array)
{
int i;
int j;
int token_len;
i = 0;
j = 0;
while (s[j] != '\0')
{
while (s[j] == delim && s[j] != '\0')
j++;
if (s[j] != delim && s[j] != '\0')
{
token_len = 0;
while (s[j + token_len] != delim && s[j + token_len] != '\0')
token_len++;
array = malloc_storage(array, i, token_len);
if (array == NULL)
return (NULL);
ft_strlcpy(array[i], &s[j], token_len + 1);
j += token_len;
i++;
}
}
array[i] = NULL;
return (array);
}
static char **malloc_storage(char **array, int i, int token_len)
{
int j;
array[i] = (char *)malloc((token_len + 1) * sizeof(char));
if (array[i] == NULL)
{
j = 0;
while (j < i)
{
free(array[j]);
j++;
}
free(array);
return (NULL);
}
return (array);
}