-
Notifications
You must be signed in to change notification settings - Fork 110
/
ft_split.c
49 lines (43 loc) · 874 Bytes
/
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
#include <stdlib.h>
#include <stdio.h>
char *ft_strncpy(char *s1, char *s2, int n)
{
int i = -1;
while (++i < n && s2[i])
s1[i] = s2[i];
s1[i] = '\0';
return (s1);
}
char **ft_split(char *str)
{
int i = 0;
int j = 0;
int k = 0;
int wc = 0;
while (str[i])
{
while (str[i] && (str[i] == ' ' || str[i] == '\t' || str[i] == '\n'))
i++;
if (str[i])
wc++;
while (str[i] && (str[i] != ' ' && str[i] != '\t' && str[i] != '\n'))
i++;
}
char **out = (char **)malloc(sizeof(char *) * (wc + 1));
i = 0;
while (str[i])
{
while (str[i] && (str[i] == ' ' || str[i] == '\t' || str[i] == '\n'))
i++;
j = i;
while (str[i] && (str[i] != ' ' && str[i] != '\t' && str[i] != '\n'))
i++;
if (i > j)
{
out[k] = (char *)malloc(sizeof(char) * ((i - j) + 1));
ft_strncpy(out[k++], &str[j], i - j);
}
}
out[k] = NULL;
return (out);
}