-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_split.c
executable file
·81 lines (72 loc) · 1.96 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
79
80
81
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jchoy-me <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/07/11 14:30:10 by jchoy-me #+# #+# */
/* Updated: 2023/07/11 14:30:11 by jchoy-me ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
/*
DESCRIPTION:
Allocates (with malloc(3)) and returns an array of strings obtained by
splitting ’s’ using the character ’c’ as a delimiter. The array must end
with a NULL pointer.
PARAMETERS:
s: The string to be split.
c: The delimiter character.
RETURN VALUE:
The array of new strings resulting from the split.
NULL if the allocation fails.
EXTERNAL FUNCTIONS:
malloc, free
*/
static int ft_nwords(char const *s, char c)
{
int i;
int nwords;
i = 0;
nwords = 0;
while (s[i] != '\0')
{
if (s[i] != c)
{
nwords++;
while (s[i] != c && s[i] != '\0')
i++;
if (s[i] == '\0')
return (nwords);
}
i++;
}
return (nwords);
}
char **ft_split(char const *s, char c)
{
int i;
int j;
int start;
char **strs;
strs = (char **) malloc (sizeof(char *) * (ft_nwords(s, c) + 1));
if (strs == NULL || s == NULL)
return (NULL);
i = 0;
j = 0;
while (j < ft_nwords(s, c))
{
if (s[i] != c)
{
start = i;
while (s[i] != c && s[i] != '\0')
i++;
strs[j] = ft_substr(s, start, i - start);
j++;
}
i++;
}
strs[j] = NULL;
return (strs);
}