-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
95 lines (86 loc) · 2.28 KB
/
Copy pathft_split.c
File metadata and controls
95 lines (86 loc) · 2.28 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jados-sa <jados-sa@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/10/20 16:47:47 by jados-sa #+# #+# */
/* Updated: 2024/10/29 19:30:26 by jados-sa ### ########.fr */
/* */
/* ************************************************************************** */
/* Allocates with malloc() and returns an array of strings obtained by *
* splitting 's' using the character as a delimiter. The array must end *
* with a NULL pointer. *
* Parameters: *
* s: the string to be slipt *
* c: the delimiter character. */
#include "libft.h"
static size_t count_tokens(char *s, char c)
{
int tokens;
int inside_token;
tokens = 1;
if (!s)
return (0);
while (*s)
{
inside_token = 0;
while (*s == c && *s)
++s;
while (*s != c && *s)
{
if (!inside_token)
{
++tokens;
inside_token = 1;
}
++s;
}
}
return (tokens);
}
static size_t token_len(char *s, char c)
{
size_t len;
len = 0;
while (s[len] != c && s[len])
len++;
return (len + 1);
}
static char **insert_token(size_t *i, char **list, char *s, char c)
{
list[*i] = (char *)malloc(token_len(s, c) * sizeof(char));
if (!list[*i])
return (NULL);
ft_strlcpy(list[*i], s, token_len(s, c));
*i += 1;
return (list);
}
char **ft_split(char *s, char c)
{
char **strs;
size_t i;
int inside_token;
strs = (char **) malloc (count_tokens(s, c) * sizeof (char *));
i = 0;
if (!s || !strs)
return (NULL);
while (*s)
{
inside_token = 0;
while (*s == c && *s)
++s;
while (*s != c && *s)
{
if (!inside_token)
{
insert_token(&i, strs, s, c);
inside_token = 1;
}
++s;
}
}
strs[i] = 0;
return (strs);
}