-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split.c
More file actions
105 lines (94 loc) · 2.34 KB
/
ft_split.c
File metadata and controls
105 lines (94 loc) · 2.34 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
95
96
97
98
99
100
101
102
103
104
105
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lcosta-g <lcosta-g@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/10/09 13:17:01 by lcosta-g #+# #+# */
/* Updated: 2024/11/01 18:24:32 by lcosta-g ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static void *clean_mem(char **mem)
{
char **temp;
temp = mem;
while (*temp)
free(*temp++);
free(mem);
return (NULL);
}
static unsigned int count_words(char const *s, char c)
{
unsigned int count;
count = 0;
while (*s)
{
while (*s == c && *s)
s++;
if (*s)
count++;
while (*s != c && *s)
s++;
}
return (count);
}
static char **split_str(char **arr, char const *s, char c)
{
char *temp;
size_t len;
size_t i;
i = 0;
while (*s)
{
while (*s && *s == c)
s++;
if (*s)
{
temp = ft_strchr(s, c);
if (temp)
len = temp - s;
else
len = ft_strlen(s);
temp = ft_substr(s, 0, len);
if (!temp)
return (clean_mem(arr));
arr[i++] = temp;
s += len;
}
}
return (arr);
}
char **ft_split(char const *s, char c)
{
char **arr;
if (!s)
return (NULL);
arr = (char **)ft_calloc((count_words(s, c) + 1), sizeof(char *));
if (!arr)
return (NULL);
return (split_str(arr, s, c));
}
/*
#include <stdio.h>
int main(void)
{
char *str;
char **splitted_str;
int i;
str = "lorem ipsum dolor sit amet,
consectetur adipiscing elit. Sed non risus. Suspendisse lectus tortor,
dignissim sit amet, adipiscing nec, ultricies sed,
dolor. Cras elementum ultricies diam. Maecenas ligula massa, varius a,
semper congue, euismod non, mi.";
i = 0;
splitted_str = ft_split(str, ' ');
if (!splitted_str)
return (1);
while (splitted_str[i])
printf("%s\n", splitted_str[i++]);
clean_mem(splitted_str);
return (0);
}
*/