-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
107 lines (96 loc) · 2.44 KB
/
ft_split.c
File metadata and controls
107 lines (96 loc) · 2.44 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
96
97
98
99
100
101
102
103
104
105
106
107
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ibravo-m <ibravo-m@student.42lisboa.com +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/04/19 17:08:37 by ibravo-m #+# #+# */
/* Updated: 2024/05/02 15:29:23 by ibravo-m ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
// splits a string into an array of words
// to free the allocated memory if anything goes wrong
static void ft_freedup(char **array)
{
int i;
i = 0;
while (array[i])
{
free(array[i]);
i++;
}
free(array);
}
// to count how many words exists in the array,
// so we know the size for the malloc
static int ft_count_words(char const *s, char delimiter)
{
int words;
int i;
i = 0;
words = 0;
while (s[i])
{
while (s[i] == delimiter && s[i])
i++;
if (s[i] && s[i] != delimiter)
words++;
while (s[i] && s[i] != delimiter)
i++;
}
return (words);
}
// to separate each word in the correct order
static char **ft_split_words(char **array, char const *s, char c)
{
char **word;
size_t word_len;
size_t i;
word = array;
word_len = 0;
i = -1;
while (s[++i])
{
if (s[i] != c)
{
word_len++;
if (s[i + 1] == '\0' || s[i + 1] == c)
{
*word = ft_substr(s, i - word_len + 1, word_len);
if (!(*word))
return (ft_freedup(array), NULL);
word++;
word_len = 0;
}
}
}
*word = NULL;
return (array);
}
char **ft_split(char const *s, char c)
{
char **array;
int size;
if (!s)
return (NULL);
size = ft_count_words(s, c);
array = malloc((size + 1) * sizeof(char *));
if (!array)
return (NULL);
array = ft_split_words(array, s, c);
return (array);
}
// int main()
// {
// char c[] = "eu sou o hugo";
// char **s = ft_split(c,' ');
// int i;
// i = 0;
// while (s[i])
// {
// printf("%s[%d]\n",s[i],i);
// i++;
// }
// }