-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
91 lines (82 loc) · 2.08 KB
/
ft_split.c
File metadata and controls
91 lines (82 loc) · 2.08 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rdragan <rdragan@student.42heilbronn.de +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/11/05 09:16:12 by rdragan #+# #+# */
/* Updated: 2023/04/24 20:58:36 by rdragan ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
/*
Returns the count of how many words are separated by 'c' in 's'
*/
static size_t list_len(const char *s, char c)
{
int state;
size_t counter;
size_t i;
counter = 0;
state = 0;
i = -1;
while (s[++i])
{
if (s[i] != c && state == 0)
{
counter++;
state = 1;
}
else if (s[i] == c && state == 1)
state = 0;
}
return (counter);
}
int add_all_words_to_split(char **list, const char *s, char c)
{
size_t i;
size_t j;
int index;
index = -1;
i = -1;
j = -1;
while (++i <= ft_strlen(s))
{
if (s[i] != c && index < 0)
index = i;
else if ((s[i] == c || i == ft_strlen(s)) && index >= 0)
{
list[++j] = ft_substr(s, index, (int)i - index);
if (!list[j])
return (0);
index = -1;
}
}
return (1);
}
/* Frees split memory */
void *free_split(char **arr)
{
int i;
i = 0;
while (arr[i])
free (arr[i++]);
free (arr);
return (NULL);
}
char **ft_split(const char *s, char c)
{
char **split;
size_t split_len;
if (!s)
return (NULL);
split_len = list_len(s, c);
split = malloc((split_len + 1) * sizeof(char *));
if (!split)
return (NULL);
if (!add_all_words_to_split(split, s, c))
return (free_split(split));
split[split_len] = NULL;
return (split);
}