-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_split.c
117 lines (104 loc) · 2.22 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mzhukova <mzhukova@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/11/16 16:35:43 by mzhukova #+# #+# */
/* Updated: 2023/11/17 13:47:39 by mzhukova ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
int count_words(const char *s, char sep)
{
int counter;
int in_word;
counter = 0;
in_word = 0;
while (*s)
{
if (*s != sep && in_word == 0)
{
in_word = 1;
counter++;
}
if (*s == sep)
in_word = 0;
s++;
}
return (counter);
}
char *allocate_word(const char *start, int len)
{
char *word;
int i;
word = malloc(len + 1);
if (!word)
return (NULL);
i = 0;
while (i < len)
{
word[i] = start[i];
i++;
}
word[len] = '\0';
return (word);
}
int word_len(char const *s, char c)
{
int len;
len = 0;
while (*s && *s != c)
{
len++;
s++;
}
return (len);
}
char **allocate_array(char const *s, char c)
{
int words;
char **result;
words = count_words(s, c);
result = malloc((words + 1) * sizeof(char *));
return (result);
}
char **ft_split(char const *s, char c)
{
int i;
int len;
char **result;
if (!s)
return (NULL);
result = allocate_array(s, c);
if (!result)
return (NULL);
i = 0;
while (*s)
{
if (*s != c)
{
len = word_len(s, c);
result[i++] = allocate_word(s, len);
s += len;
}
else
s++;
}
result[i] = NULL;
return (result);
}
// #include <stdio.h>
// int main(void)
// {
// char *s1 = "ab,abc,,sggs,";
// char del = ',';
// char **res = ft_split(s1, del);
// int i = 0;
// while(res[i]){
// printf("Result: %s\n", res[i]);
// i++;
// }
// return (0);
// }