-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
111 lines (100 loc) · 2.39 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
111
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: agarijo- <agarijo-@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/10/11 10:22:12 by agarijo- #+# #+# */
/* Updated: 2023/03/24 15:26:29 by agarijo- ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_count_words_s(char const *s, char c)
{
int counter;
int amount;
int flag;
amount = 0;
counter = 0;
flag = 0;
while (*(s + counter))
{
if (*(s + counter) != c && flag != 1)
{
amount++;
flag = 1;
}
else if (*(s + counter) == c)
flag = 0;
counter++;
}
return (amount);
}
static int ft_size_word(const char *word, char c)
{
int counter;
counter = 0;
while (*(word + counter))
{
if (*(word + counter) == c)
return (counter);
counter++;
}
return (counter);
}
static char *ft_ins_word(const char *s, int word_counter)
{
int counter;
char *word;
counter = 0;
word = malloc((word_counter + 1) * sizeof(char));
if (!word)
return (NULL);
while (word_counter--)
{
*(word + counter) = *s++;
counter++;
}
*(word + counter) = '\0';
return (word);
}
void free_memory(char **result_array)
{
int counter;
counter = 0;
while (result_array[counter])
{
free(result_array[counter]);
result_array[counter] = NULL;
counter ++;
}
free(result_array);
}
char **ft_split(const char *s, char c)
{
int cr;
int flag;
int r_a_c;
char **r_a;
cr = 0;
flag = 0;
r_a_c = 0;
r_a = ft_calloc((ft_count_words_s(s, c) + 1), sizeof(char *));
if (!r_a)
return (NULL);
while (*(s + cr))
{
if (*(s + cr) != c && flag != 1)
{
*(r_a + r_a_c) = ft_ins_word((s + cr), ft_size_word((s + cr), c));
if (!*(r_a + r_a_c++))
return (free_memory(r_a), NULL);
flag = 1;
}
else if (*(s + cr) == c)
flag = 0;
cr++;
}
return (*(r_a + r_a_c) = NULL, r_a);
}