-
Notifications
You must be signed in to change notification settings - Fork 4
/
ft_strsplit.c
92 lines (82 loc) · 2.06 KB
/
ft_strsplit.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strsplit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: vbrazhni <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/07/02 19:09:23 by vbrazhni #+# #+# */
/* Updated: 2018/07/02 19:09:24 by vbrazhni ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#include <stdlib.h>
static size_t ft_count_words(char const *s, char c)
{
size_t words;
words = 0;
while (*s)
{
while (*s == c)
s++;
if (*s)
{
words++;
while (*s && *s != c)
s++;
}
}
return (words);
}
static char *ft_get_word(char *word, char c)
{
char *start;
start = word;
while (*word && *word != c)
word++;
*word = '\0';
return (ft_strdup(start));
}
static void ft_free_words(char **words, size_t i)
{
while (i--)
ft_strdel(&(words[i]));
free(*words);
}
static char **ft_get_words(char *s, char c, size_t words_count)
{
char **words;
char *word;
size_t i;
i = 0;
if ((words = (char **)ft_memalloc(sizeof(char *) * (words_count + 1))))
{
while (i < words_count)
{
while (*s == c)
s++;
if (*s)
{
if (!(word = ft_get_word(s, c)))
{
ft_free_words(words, i);
return (NULL);
}
words[i++] = word;
s += (ft_strlen(word) + 1);
}
}
words[i] = NULL;
}
return (words);
}
char **ft_strsplit(char const *s, char c)
{
char **words;
char *line;
if (!s || !(line = ft_strdup((char *)s)))
return (NULL);
words = ft_get_words(line, c, ft_count_words(line, c));
free(line);
return (words);
}