aboutsummaryrefslogtreecommitdiffstats
path: root/src/ft_split.c
blob: bb51c8564fb79c50f63cfe32f5727ae4a4214904 (plain)
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
#include "libft.h"
#include <stdlib.h>

static size_t
_s_count_words (char const *s, char c)
{
  size_t count;

  count = 0;
  while (*s)
    {
      while (*s == c)
        s++;
      if (*s)
        {
          count++;
          while (*s && *s != c)
            s++;
        }
    }
  return (count);
}

static void
_s_free_all (char **arr, size_t n)
{
  size_t i;

  i = 0;
  while (i < n)
    free (arr[i++]);
  free (arr);
}

char **
ft_split (char const *s, char c)
{
  size_t count;
  char **arr;
  size_t i;

  count = _s_count_words (s, c);
  arr = malloc ((count + 1) * sizeof (char *));
  if (!arr)
    return (NULL);
  i = 0;
  while (*s)
    {
      while (*s == c)
        s++;
      if (*s)
        {
          const char *start = s;
          while (*s && *s != c)
            s++;
          arr[i] = ft_substr (start, 0, s - start);
          if (!arr[i])
            {
              _s_free_all (arr, i);
              return (NULL);
            }
          i++;
        }
    }
  arr[i] = NULL;
  return (arr);
}