-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
92 lines (82 loc) · 1.99 KB
/
ft_split.c
File metadata and controls
92 lines (82 loc) · 1.99 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: phelebra <xhelp00@gmail.com> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/01/13 10:39:39 by phelebra #+# #+# */
/* Updated: 2023/01/23 09:56:43 by phelebra ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_wordcount(char const *s, char c)
{
int wordcount;
int i;
wordcount = 0;
i = 0;
while (s[i])
{
while (s[i] == c)
i++;
if (s[i])
wordcount++;
while (s[i] && s[i] != c)
i++;
}
return (wordcount);
}
static int ft_size_word(char const *s, char c)
{
int size;
size = 0;
while (s[size] != c && s[size])
{
size++;
}
return (size);
}
static void ft_free(char **strs, int j)
{
while (j-- > 0)
free(strs[j]);
free(strs);
}
static char **ft_fill(char **new, const char *str, char c, int count)
{
int words;
int len;
int i;
i = 0;
words = 0;
while (words < count)
{
while (str[i] == c)
i++;
len = ft_size_word(&str[i], c);
new[words] = ft_substr(str, i, len);
if (!new[words])
{
ft_free(new, words);
return (NULL);
}
while (str[i] && str[i] != c)
i++;
words++;
}
new[words] = NULL;
return (new);
}
char **ft_split(const char *str, char c)
{
int count;
char **new;
if (!str)
return (NULL);
count = ft_wordcount(str, c);
new = malloc ((count + 1) * sizeof(char **));
if (!new)
return (NULL);
return (ft_fill(new, str, c, count));
}