-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
71 lines (64 loc) · 1.7 KB
/
ft_split.c
File metadata and controls
71 lines (64 loc) · 1.7 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: muganiev <gf.black.tv@gmail.com> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/05/26 15:14:04 by muganiev #+# #+# */
/* Updated: 2022/05/31 17:58:36 by muganiev ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int count_words(char const *s, char c)
{
int words;
int i;
words = 0;
i = 0;
if (c < 0)
return (0);
if (s[0] != c)
words++;
while (s[i] != '\0' && s[i + 1] != '\0')
{
if (s[i] == c && s[i + 1] != c)
words++;
i++;
}
return (words);
}
static int word_len(const char *s, char c, int start)
{
int i;
i = 0;
while (s[start + i] != c && s[start + i] != '\0')
i++;
return (i);
}
char **ft_split(char const *s, char c)
{
char **ptr;
int i;
int start;
if (!s)
return (NULL);
ptr = (char **)malloc(sizeof(char *) * (count_words(s, c) + 1));
if (!ptr)
return (NULL);
i = 0;
start = 0;
while (s[i] != '\0')
{
if (s[i] != c)
{
ptr[start] = ft_substr(s, i, word_len(s, c, i));
i = i + word_len(s, c, i);
start++;
}
else
i++;
}
ptr[start] = NULL;
return (ptr);
}