libft
ft_strsplit.c
Go to the documentation of this file.
1 /* ************************************************************************** */
3 /* */
4 /* ::: :::::::: */
5 /* ft_strsplit.c :+: :+: :+: */
6 /* +:+ +:+ +:+ */
7 /* By: unite <marvin@42.fr> +#+ +:+ +#+ */
8 /* +#+#+#+#+#+ +#+ */
9 /* Created: 2019/09/05 13:31:18 by unite #+# #+# */
10 /* Updated: 2020/07/16 02:43:07 by unite ### ########.fr */
11 /* */
12 /* ************************************************************************** */
13 
14 #include "libft.h"
15 #include <stdlib.h>
16 
17 static void free_tab(char **tab)
18 {
19  int i;
20 
21  i = 0;
22  while (tab[i])
23  free(tab[i++]);
24  free(tab);
25 }
26 
27 static const char *search_delim(const char *s, char delim)
28 {
29  while (*s && *s != delim)
30  s++;
31  return (s);
32 }
33 
34 static const char *search_not_delim(const char *s, char delim)
35 {
36  while (*s && *s == delim)
37  s++;
38  return (s);
39 }
40 
41 static size_t count_words(const char *s, char delim)
42 {
43  size_t count;
44 
45  count = 0;
46  s = search_not_delim(s, delim);
47  while (*s)
48  {
49  count++;
50  s = search_delim(s, delim);
51  s = search_not_delim(s, delim);
52  }
53  return (count);
54 }
55 
70 char **ft_strsplit(char const *s, char delim)
71 {
72  char **tab;
73  const char *start;
74  const char *end;
75  size_t wcount;
76  size_t i;
77 
78  wcount = count_words(s, delim);
79  if (!(tab = ft_memalloc(sizeof(char *) * (wcount + 1))))
80  return (NULL);
81  i = 0;
82  end = s;
83  while (i < wcount)
84  {
85  start = search_not_delim(end, delim);
86  end = search_delim(start, delim);
87  if (!(tab[i] = ft_strndup(start, end - start)))
88  {
89  free_tab(tab);
90  return (NULL);
91  }
92  i++;
93  }
94  tab[i++] = NULL;
95  return (tab);
96 }
libft.h
ft_strsplit
char ** ft_strsplit(char const *s, char delim)
Splits a string on whitespace characters.
Definition: ft_strsplit.c:70
ft_memalloc
void * ft_memalloc(size_t size)
Allocates memory of a given size and initializes it to 0.
Definition: ft_memalloc.c:24
ft_strndup
char * ft_strndup(const char *s1, size_t len)
Makes a new string and copies up to len characters to it.
Definition: ft_strndup.c:30