-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
76 lines (68 loc) · 2.01 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: almarcos <almarcos@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/08/03 14:22:35 by almarcos #+# #+# */
/* Updated: 2023/08/06 13:55:15 by almarcos ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t ft_word_count(const char *s, int c);
static char **ft_alloc_words(char **array, const char *s, int c);
char **ft_split(char const *s, char c)
{
char **array;
size_t words;
if (!s)
return (NULL);
words = ft_word_count(s, c);
array = (char **)ft_calloc((words + 1), sizeof(char *));
if (!array)
return (NULL);
while (*s == (unsigned char)c && *s)
s++;
ft_alloc_words(array, s, c);
return (array);
}
static size_t ft_word_count(const char *s, int c)
{
size_t words;
words = 0;
while (*s)
{
if (*s != c)
{
words++;
while (*s != c && *s)
s++;
}
if (*s == '\0')
return (words);
s++;
}
return (words);
}
static char **ft_alloc_words(char **array, const char *s, int c)
{
size_t current_word_len;
size_t index;
index = 0;
while (*s)
{
current_word_len = 0;
while (s[current_word_len] != c && s[current_word_len])
current_word_len++;
array[index] = (char *)ft_calloc((current_word_len + 1), sizeof(char));
ft_strlcpy(array[index], s, current_word_len + 1);
index++;
while (*s != c && *s)
s++;
while (*s == c && *s)
s++;
}
array[index] = NULL;
return (array);
}