-
Notifications
You must be signed in to change notification settings - Fork 1
/
ft_split.c
executable file
·102 lines (91 loc) · 2.19 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rel-fila <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/10/16 15:08:32 by rel-fila #+# #+# */
/* Updated: 2022/10/16 15:10:19 by rel-fila ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#include <stdio.h>
static int ft_countword(char *str, char c)
{
int i;
int count;
count = 0;
i = 0;
while (str[i] != '\0')
{
while (str[i] != '\0' && (str[i] == c))
i++;
if (str[i] != '\0')
count++;
while (str[i] != '\0' && !(str[i] == c))
i++;
}
return (count);
}
static int ft_wordlen(char *str, char c)
{
int i;
i = 0;
while (str[i] != '\0' && str[i] != c)
{
i++;
}
return (i);
}
static char *ft_word(char *str, char c)
{
int len_word;
int i;
char *word;
i = 0;
len_word = ft_wordlen(str, c);
word = (char *)malloc(sizeof(char) * (len_word + 1));
while (i < len_word)
{
word[i] = str[i];
i++;
}
word[i] = '\0';
return (word);
}
static void freestring(char **string, int i)
{
int a;
a = 0;
while (a <= i)
free(string[i++]);
free(string);
}
char **ft_split(char *str, char c)
{
char **strings;
int i;
i = 0;
if (str == NULL)
return (NULL);
strings = (char **)malloc(sizeof(char *) * (ft_countword(str, c) + 1));
if (strings == NULL)
return (NULL);
while (*str != '\0')
{
while (*str != '\0' && (*str == c))
str++;
if (*str != '\0')
strings[i++] = ft_word(str, c);
if (i > 0 && strings[i - 1] == NULL)
{
freestring(strings, i - 1);
return (NULL);
}
while (*str && !(*str == c))
str++;
}
strings[i] = 0;
return (strings);
}