-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
94 lines (84 loc) · 1.46 KB
/
ft_split.c
File metadata and controls
94 lines (84 loc) · 1.46 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
//NOT Done
//Check1 - FALSE
//
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include "libft.h"
static int char_is_separator(char c, char sep)
{
int i;
i = 0;
if (c == sep || c == '\0')
return (1);
return (0);
}
static int count_words(char *str, char sep)
{
int i;
int words;
words = 0;
i = 0;
while (str[i] != '\0')
{
if (char_is_separator(str[i + 1], sep) == 1
&& char_is_separator(str[i], sep) == 0)
words++;
i++;
}
return (words);
}
static void write_word(char *dest, char *from, char sep)
{
int i;
i = 0;
while (char_is_separator(from[i], sep) == 0)
{
dest[i] = from[i];
i++;
}
dest[i] = '\0';
}
static void *write_split(char **split, char *str, char sep)
{
int i;
int j;
int word;
word = 0;
i = 0;
while (str[i] != '\0')
if (char_is_separator(str[i], sep) == 1)
i++;
else
{
j = 0;
while (char_is_separator(str[i + j], sep) == 0)
j++;
if ((split[word] = (char*)malloc(sizeof(char) * (j + 1))) == NULL)
{
while (word > 0)
free(split[--word]);
return (NULL);
}
write_word(split[word], str + i, sep);
i += j;
word++;
}
return ((void*)1);
}
char **ft_split(const char *s, char c)
{
char **res;
char *str;
int words;
if (s == NULL)
return (NULL);
str = (char*)s;
words = count_words(str, c);
if ((res = (char**)malloc(sizeof(char*) * (words + 1))) == NULL)
return (NULL);
res[words] = 0;
if (write_split(res, str, c) == NULL)
return (NULL);
return (res);
}