-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
124 lines (111 loc) · 2.49 KB
/
Copy pathft_split.c
File metadata and controls
124 lines (111 loc) · 2.49 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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: licohen <licohen@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/05/19 17:11:11 by licohen #+# #+# */
/* Updated: 2024/05/28 14:37:23 by licohen ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
void ft_free_tab(char **tab, int size)
{
int i;
i = 0;
while (i < size)
{
free(tab[i]);
i++;
}
free(tab);
}
static int ft_count_words(const char *str, char c)
{
int nb_words;
int i;
nb_words = 0;
i = 0;
while (str[i] != '\0')
{
if (str[i] != c && (i == 0 || str[i - 1] == c))
nb_words++;
i++;
}
return (nb_words);
}
static char *fill_word(char *str, char const *s, int i, int len)
{
int j;
j = 0;
while (len > 0)
{
str[j] = s[i - len];
j++;
len--;
}
str[j] = '\0';
return (str);
}
char **ft_div_words(char const *s, char c, char **tab, int nb_word)
{
int i;
int k;
int len;
i = 0;
k = 0;
while (k < nb_word)
{
len = 0;
while (s[i] && s[i] == c)
i++;
while (s[i] && s[i] != c)
{
i++;
len++;
}
tab[k] = (char *)malloc(sizeof(char) * (len + 1));
if (!tab[k])
{
ft_free_tab(tab, k);
return (NULL);
}
fill_word(tab[k++], s, i, len);
}
return (tab);
}
char **ft_split(char const *s, char c)
{
char **tab;
unsigned int nb_words;
if (!s)
return (NULL);
nb_words = ft_count_words(s, c);
tab = (char **)malloc(sizeof(char *) * (nb_words + 1));
if (!tab)
return (NULL);
tab = ft_div_words(s, c, tab, nb_words);
if (!tab)
return (NULL);
tab[nb_words] = NULL;
return (tab);
}
// int main (void)
// {
// char *s = "Hello comment tu vas";
// char c = ' ';
// char **result = ft_split(s, c);
// int i;
// i = 0;
// if (result)
// {
// while (result[i] != NULL)
// {
// printf("%s\n", result[i]);
// i++;
// free(result);
// }
// }
// return (0);
// }