-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
80 lines (72 loc) · 1.94 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: edesaint <edesaint@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/11/20 17:43:33 by edesaint #+# #+# */
/* Updated: 2022/12/06 19:49:02 by edesaint ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdio.h>
#include "libft.h"
static void ft_free(char **tab, int i)
{
while (i-- > 0)
free(tab[i]);
free(tab);
}
static int ft_nb_words(char const *str, char c)
{
int words;
int i;
words = 0;
i = 0;
while (str[i])
{
while (str[i] && str[i] == c)
i++;
if (str[i])
words++;
while (str[i] && str[i] != c)
i++;
}
return (words);
}
static void ft_create(char **tab, char const *str, char c, size_t nb_words)
{
size_t i;
size_t j;
size_t len_str;
len_str = 0;
i = 0;
j = 0;
while (str[len_str + i] && j < nb_words)
{
while (str[len_str + i] && str[len_str + i] == c)
len_str++;
while (str[len_str + i] && str[len_str + i] != c)
i++;
tab[j] = ft_substr(str, len_str, i);
if (!tab[j++])
ft_free(tab, --j);
len_str += i;
i = 0;
}
if (tab != NULL)
tab[j] = NULL;
}
char **ft_split(char const *s, char c)
{
char **tab;
size_t nb_words;
if (!s)
return (NULL);
nb_words = ft_nb_words(s, c);
tab = (char **) malloc(sizeof(char *) * (nb_words + 1));
if (!tab)
return (NULL);
ft_create(tab, s, c, nb_words);
return (tab);
}