-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_split.c
104 lines (94 loc) · 2.19 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jergoh <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/09/21 10:25:27 by jergoh #+# #+# */
/* Updated: 2023/09/21 10:25:30 by jergoh ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static char **free_array(char **ptr, int i)
{
while (i > 0)
{
i--;
free(ptr[i]);
}
free(ptr);
return (0);
}
static int ft_count_words(char const *str, char c)
{
int i;
int count;
i = 0;
count = 0;
while (str[i] != '\0')
{
if (str[i] == c)
i++;
else
{
count++;
while (str[i] && str[i] != c)
i++;
}
}
return (count);
}
static char *ft_putword(char *word, char const *s, int i, int word_len)
{
int j;
j = 0;
while (word_len > 0)
{
word[j] = s[i - word_len];
j++;
word_len--;
}
word[j] = '\0';
return (word);
}
static char **ft_split_words(char const *s, char c, char **s2, int num_words)
{
int i;
int word;
int word_len;
i = 0;
word = 0;
word_len = 0;
while (word < num_words)
{
while (s[i] && s[i] == c)
i++;
while (s[i] && s[i] != c)
{
i++;
word_len++;
}
s2[word] = (char *)malloc(sizeof(char) * (word_len + 1));
if (!s2[word])
return (free_array(s2, word));
ft_putword(s2[word], s, i, word_len);
word_len = 0;
word++;
}
s2[word] = 0;
return (s2);
}
char **ft_split(char const *s, char c)
{
char **s2;
unsigned int num_words;
if (!s)
return (0);
num_words = ft_count_words(s, c);
s2 = (char **)malloc(sizeof(char *) * (num_words + 1));
if (!s2)
return (0);
s2 = ft_split_words(s, c, s2, num_words);
return (s2);
}