This repository has been archived by the owner on Apr 19, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_split.c
78 lines (69 loc) · 1.75 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tkhemniw <gt.khemniwat@gmail.com> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/08/31 20:21:30 by tkhemniw #+# #+# */
/* Updated: 2022/08/31 20:22:00 by tkhemniw ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t wordcount(char const *s, char c)
{
size_t count;
count = 0;
while (*s)
{
while (*s == c && *s)
s++;
if (*s != c && *s)
count++;
while (*s != c && *s)
s++;
}
return (count);
}
static size_t wordlen(char const *s, char c)
{
size_t len;
len = 0;
while (s[len] && s[len] != c)
len++;
return (len);
}
static char *wordcpy(char const *s, char c)
{
char *str;
str = malloc(wordlen(s, c) + 1);
if (!str)
return (NULL);
ft_strlcpy(str, s, wordlen(s, c) + 1);
return (str);
}
char **ft_split(char const *s, char c)
{
char **res;
size_t i;
i = 0;
if (!s)
return (NULL);
res = malloc((wordcount(s, c) + 1) * sizeof(char *));
if (!res)
return (NULL);
while (*s)
{
while (*s && *s == c)
s++;
if (*s != c && *s)
{
res[i] = wordcpy(s, c);
i++;
}
while (*s && *s != c)
s++;
}
res[i] = NULL;
return (res);
}