tgrekov-pipex
HIVE pipex May 2024
Loading...
Searching...
No Matches
ft_split.c
Go to the documentation of this file.
1/* ************************************************************************** */
2/* */
3/* ::: :::::::: */
4/* ft_split.c :+: :+: :+: */
5/* +:+ +:+ +:+ */
6/* By: tgrekov <tgrekov@student.hive.fi> +#+ +:+ +#+ */
7/* +#+#+#+#+#+ +#+ */
8/* Created: 2023/10/26 15:41:34 by tgrekov #+# #+# */
9/* Updated: 2023/11/13 22:11:57 by tgrekov ### ########.fr */
10/* */
11/* ************************************************************************** */
12
20#include "libft.h"
21
22static size_t count_sections(char const *s, char c)
23{
24 size_t i;
25 size_t sections;
26
27 sections = 0;
28 i = 0;
29 while (s[i])
30 {
31 if (s[i] != c && (!i || s[i - 1] == c))
32 sections++;
33 i++;
34 }
35 return (sections);
36}
37
38static char **free_all(char **arr)
39{
40 size_t i;
41
42 i = 0;
43 while (arr[i])
44 free(arr[i++]);
45 free(arr);
46 return (0);
47}
48
49static size_t end_of_word(char const *s, char c)
50{
51 size_t i;
52
53 i = 0;
54 while (s[i])
55 {
56 if (s[i] == c)
57 return (i);
58 i++;
59 }
60 return (ft_strlen(s));
61}
62
72char **ft_split(char const *s, char c)
73{
74 char **arr;
75 size_t arr_i;
76 size_t len;
77
78 while (*s && *s == c)
79 s++;
80 arr = ft_calloc(count_sections(s, c) + 1, sizeof(char *));
81 if (!arr)
82 return (0);
83 arr_i = 0;
84 while (*s)
85 {
86 len = end_of_word(s, c);
87 arr[arr_i] = ft_substr(s, 0, len);
88 if (!arr[arr_i++])
89 return (free_all(arr));
90 s += len;
91 while (*s && *s == c)
92 s++;
93 }
94 return (arr);
95}
void * ft_calloc(size_t count, size_t size)
Allocates count * size bytes with malloc and returns a pointer to the result.
Definition ft_calloc.c:34
char ** ft_split(char const *s, char c)
Split string s by characer c into allocated array of strings, with NULL as the last element.
Definition ft_split.c:72
size_t ft_strlen(const char *str)
Get length of str.
Definition ft_strlen.c:28
char * ft_substr(char const *s, unsigned int start, size_t len)
Allocates and returns a substring of s, starting at s + start, and ending no later than s + start + l...
Definition ft_substr.c:32