-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_strsplit_bonus.c
83 lines (75 loc) · 2.28 KB
/
ft_strsplit_bonus.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strsplit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aviholai <aviholai@student.hive.fi> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/02/02 17:14:23 by aviholai #+# #+# */
/* Updated: 2022/02/10 15:12:10 by aviholai ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
/*
** 'Strsplit()' (string split) allocates memory and returns a table of strings
** after splitting given source '*s' by every given character 'c'. If the
** allocation fails it should return 'NULL'.
** The file runs in three parts: a function for word counting, a function for
** duplicating strings, and finally, the string splitter itself.
** We apply a static variable in use for the word count as ways of getting
** around not having to use a global variable and be able to and be able to
** maintain a sattue of value in-between invocations.
*/
static int ft_wordcount(char const *s, char c)
{
unsigned int i;
int count;
i = 0;
count = 0;
while (s[i])
{
while (s[i] == c)
i++;
if (s[i] != '\0')
count++;
while (s[i] && (s[i] != c))
i++;
}
return (count);
}
static char *ft_strndup(const char *s, size_t n)
{
char *str;
str = (char *)malloc(sizeof(char) * n + 1);
if (str == NULL)
return (NULL);
str = ft_strncpy(str, s, n);
str[n] = '\0';
return (str);
}
char **ft_strsplit(char const *s, char c)
{
int i;
int i2;
int i3;
char **dst;
if (s == NULL)
return (NULL);
i = 0;
i3 = 0;
dst = (char **)malloc(sizeof(char *) * (ft_wordcount(s, c)) + 1);
if (dst == NULL)
return (NULL);
while (s[i])
{
while (s[i] == c)
i++;
i2 = i;
while (s[i] && s[i] != c)
i++;
if (i > i2)
dst[i3++] = ft_strndup(s + i2, i - i2);
}
dst[i3] = NULL;
return (dst);
}