-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_split_whitespaces.c
More file actions
99 lines (91 loc) · 2.37 KB
/
ft_split_whitespaces.c
File metadata and controls
99 lines (91 loc) · 2.37 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split_whitespaces.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: knzeng-e <knzeng-e@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/03/30 18:38:09 by knzeng-e #+# #+# */
/* Updated: 2016/03/30 18:38:23 by knzeng-e ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_count_splits(char *s)
{
int nb;
int cmp;
nb = 0;
cmp = 0;
while (s[nb])
{
while (s[nb] && (s[nb] == ' ' || s[nb] == '\n' || s[nb] == '\t'))
nb++;
if (s[nb])
cmp++;
while (s[nb] && (s[nb] != ' ' && s[nb] != '\n' && s[nb] != '\t'))
nb++;
}
return (cmp);
}
static char **ft_real_str(const char *s, int splits_nbr)
{
int i[2];
int nb;
char **tab;
i[0] = 0;
i[1] = 0;
nb = 0;
if (!(tab = (char **)malloc(sizeof(char *) * splits_nbr + 1)))
return (NULL);
tab[splits_nbr] = NULL;
while (s[nb])
while (i[0] < splits_nbr)
{
while (s[nb] && (s[nb] == ' ' || s[nb] == '\n' || s[nb] == '\t'))
nb++;
if (s[nb])
i[1] = nb;
while (s[nb] && (s[nb] != ' ' && s[nb] != '\n' && s[nb] != '\t'))
nb++;
tab[i[0]] = ft_strsub(s, i[1], nb - i[1]);
if (!tab[i[0]])
return (tab);
i[0]++;
}
return (tab);
}
static char **ft_return_exception(int sn, char **t, char *trimmed)
{
if (sn == 0)
{
t[0] = NULL;
t[1] = NULL;
}
else
{
t[0] = trimmed;
t[1] = NULL;
}
return (t);
}
char **ft_split_whitespaces(const char *s)
{
char **tab;
char *trimmed;
int splits_nbr;
if (!s)
return (NULL);
trimmed = ft_strtrim(s);
if (!trimmed)
return (NULL);
splits_nbr = ft_count_splits(trimmed);
if (splits_nbr == 0 || splits_nbr == 1)
{
if (!(tab = (char **)malloc(sizeof(char *) * 2)))
return (NULL);
ft_return_exception(splits_nbr, tab, trimmed);
}
else
tab = ft_real_str(trimmed, splits_nbr);
return (tab);
}