-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsplit.c
More file actions
79 lines (72 loc) · 1.07 KB
/
split.c
File metadata and controls
79 lines (72 loc) · 1.07 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
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
char *ft_strndup(char *src, int len)
{
char *entry;
char *ptr;
entry = malloc(len + 1);
ptr = entry;
if (entry == NULL)
return (NULL);
while (len-- && *src)
*entry++ = *src++;
*entry = '\0';
return (ptr);
}
bool check_sep(char c, char *sep)
{
while (*sep)
{
if (c == *sep)
return (true);
sep++;
}
return (false);
}
int count_words(char *str, char *sep)
{
int count;
int len;
count = 0;
len = 0;
while (*str)
{
if (check_sep(*str, sep))
{
if (len > 0)
count++;
len = 0;
}
if (!check_sep(*str, sep))
len++;
str++;
}
if (len > 0)
count++;
return (count);
}
char **split(char *str, char *charset)
{
char **strs;
int word_count;
int i;
int len;
i = 0;
word_count = count_words(str, charset);
strs = (char **)malloc(sizeof(char *) * (word_count + 1));
while (i < word_count)
{
len = 0;
while (*str)
{
if (check_sep(*str++, charset))
break ;
len++;
}
if (len > 0)
strs[i++] = strndup(str - (len + 1), len);
}
strs[i] = 0;
return (strs);
}