-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
79 lines (70 loc) · 1.77 KB
/
ft_split.c
File metadata and controls
79 lines (70 loc) · 1.77 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: moel-asr <moel-asr@student.1337.ma> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/10/10 10:33:07 by moel-asr #+# #+# */
/* Updated: 2022/10/18 16:03:33 by moel-asr ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_sep(char c1, char c2)
{
int i;
i = 0;
if (c1 == c2)
return (1);
return (0);
}
static int ft_count_words(char const *s, char c)
{
int i;
int words;
i = 0;
words = 0;
while (s[i])
{
if ((!ft_sep(s[i], c) && ft_sep(s[i - 1], c)) || (i == 0 && s[0] != c))
words++;
i++;
}
return (words);
}
static void ft_split_core(char const *s, char **strs, int words, char c)
{
int i;
int j;
int start;
i = 0;
j = 0;
while (i < words)
{
while (s[j] == c)
j++;
start = j;
while (s[j])
{
if (s[j] == c)
break ;
j++;
}
strs[i] = ft_substr(s, start, j - start);
i++;
}
strs[i] = NULL;
}
char **ft_split(char const *s, char c)
{
int words;
char **strs;
if (!s)
return (NULL);
words = ft_count_words(s, c);
strs = (char **)malloc(sizeof(char *) * words + 1);
if (!strs)
return (NULL);
ft_split_core(s, strs, words, c);
return (strs);
}