-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_split.c
110 lines (100 loc) · 2.54 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
107
108
109
110
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dapetros <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/01/24 21:58:17 by dapetros #+# #+# */
/* Updated: 2024/01/25 14:47:23 by dapetros ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t get_words_count(char const *s, const char c)
{
size_t words_count;
size_t i;
i = 0;
words_count = 0;
while (s[i])
{
if (s[i] == c)
++i;
else
{
++words_count;
while (s[i] != c && s[i])
++i;
}
}
return (words_count);
}
static size_t word_len(size_t i, char const *str, const char c)
{
size_t size;
size = 0;
while (str[i] && str[i] != c)
{
++size;
++i;
}
return (size);
}
static int split_str(char *str, char **words, char c, t_indexes *sp_ind)
{
while (str[sp_ind->i])
{
if (str[sp_ind->i] != c)
{
words[sp_ind->j] = (char *)malloc(word_len(sp_ind->i, str, c) + 1);
if (!words[sp_ind->j])
return (sp_ind->alloc_count);
else
++sp_ind->alloc_count;
sp_ind->k = 0;
while (str[sp_ind->i] && str[sp_ind->i] != c)
words[sp_ind->j][sp_ind->k++] = str[sp_ind->i++];
words[sp_ind->j][sp_ind->k] = '\0';
++sp_ind->j;
}
else
++sp_ind->i;
}
return (sp_ind->alloc_count);
}
static void ft_free(char **words, size_t alloc_count)
{
size_t i;
i = 0;
while (i < alloc_count)
{
free(words[i]);
++i;
}
free(words);
}
char **ft_split(char const *s, char c)
{
size_t words_count;
size_t alloc_count;
char **words;
t_indexes split_indexes;
if (!s)
return (NULL);
words_count = get_words_count(s, c);
words = (char **)malloc(sizeof(char *) * (words_count + 1));
if (!words)
return (NULL);
split_indexes.i = 0;
split_indexes.j = 0;
split_indexes.k = 0;
split_indexes.alloc_count = 0;
alloc_count = split_str((char *)s, words, c, &split_indexes);
if (alloc_count < words_count)
{
ft_free(words, alloc_count);
return (NULL);
}
words[words_count] = 0;
return (words);
}