-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_strsplit.c
68 lines (61 loc) · 1.87 KB
/
ft_strsplit.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strsplit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mschumac <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/06/15 20:41:35 by mschumac #+# #+# */
/* Updated: 2017/06/24 01:01:50 by mschumac ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int substring_length(char const *s, char c)
{
int i;
i = 0;
while (s[i] != c && s[i] != '\0')
i++;
return (i);
}
static int s_counter(char const *s, char c)
{
int substring_counter;
if (s == NULL)
return (0);
substring_counter = 0;
while (*s != '\0')
{
if (*s == c && *(s + 1) != c && *(s + 1) != '\0')
substring_counter++;
s++;
}
return (substring_counter);
}
char **ft_strsplit(char const *s, char c)
{
char **substrings;
int len_current_substring;
int i;
substrings = (char **)malloc(sizeof(char*) * (s_counter(s, c) + 1));
if (substrings == NULL || s == NULL)
return (NULL);
i = 0;
while (*s != '\0')
{
len_current_substring = substring_length(s, c);
if (len_current_substring)
{
substrings[i] = ft_strnew(len_current_substring);
if (substrings[i] == NULL)
return (NULL);
substrings[i] = ft_strsub(s, 0, len_current_substring);
i++;
s += len_current_substring;
}
else
s++;
}
substrings[i] = NULL;
return (substrings);
}