-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathft_split.c
More file actions
77 lines (70 loc) · 1.71 KB
/
ft_split.c
File metadata and controls
77 lines (70 loc) · 1.71 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: nnuno-ca <nnuno-ca@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/10/11 19:42:18 by roramos #+# #+# */
/* Updated: 2023/01/27 19:05:50 by nnuno-ca ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int words_counter(char const *s, char c)
{
int words;
int flag;
int i;
words = 0;
flag = 0;
i = 0;
while (s[i])
{
if (s[i] != c && flag == 0)
{
flag = 1;
words++;
}
else if (s[i] == c)
flag = 0;
i++;
}
return (words);
}
static int letters_in_word(char const *s, char c, int i)
{
int size;
size = 0;
while (s[i] && s[i] != c)
{
size++;
i++;
}
return (size);
}
char **ft_split(char const *s, char c)
{
int i;
int j;
int word;
char **str;
if (!s)
return (NULL);
i = 0;
j = -1;
word = words_counter(s, c);
str = malloc((word + 1) * sizeof(char *));
if (!str)
return (NULL);
while (++j < word)
{
while (s[i] == c)
i++;
str[j] = ft_substr(s, i, letters_in_word(s, c, i));
if (!str)
return (NULL);
i += letters_in_word(s, c, i);
}
str[j] = NULL;
return (str);
}