/ fdf / fdf / libft / ft_split.c
ft_split.c
  1  /* ************************************************************************** */
  2  /*                                                                            */
  3  /*                                                        :::      ::::::::   */
  4  /*   ft_split.c                                         :+:      :+:    :+:   */
  5  /*                                                    +:+ +:+         +:+     */
  6  /*   By: gychoi <marvin@42.fr>                      +#+  +:+       +#+        */
  7  /*                                                +#+#+#+#+#+   +#+           */
  8  /*   Created: 2022/07/11 16:20:52 by gychoi            #+#    #+#             */
  9  /*   Updated: 2022/07/14 20:00:18 by gychoi           ###   ########.fr       */
 10  /*                                                                            */
 11  /* ************************************************************************** */
 12  
 13  #include "libft.h"
 14  
 15  static size_t	word_count(char const *s, char c)
 16  {
 17  	size_t	count;
 18  	size_t	i;
 19  
 20  	count = 0;
 21  	i = 0;
 22  	while (s[i] != '\0')
 23  	{
 24  		while (s[i] != '\0' && s[i] == c)
 25  			i++;
 26  		if (s[i] != '\0' && s[i] != c)
 27  			count ++;
 28  		while (s[i] != '\0' && s[i] != c)
 29  			i++;
 30  	}
 31  	return (count);
 32  }
 33  
 34  static char	*add_word(char const *s, char c, int i)
 35  {
 36  	size_t	j;
 37  	size_t	len;
 38  	char	*word;
 39  
 40  	len = 0;
 41  	while (s[i + len] != '\0' && s[i + len] != c)
 42  		len++;
 43  	word = malloc(sizeof(char) * len + 1);
 44  	if (!word)
 45  		return (NULL);
 46  	j = 0;
 47  	while (s[i + j] != '\0' && s[i + j] != c)
 48  	{
 49  		word[j] = s[i + j];
 50  		j++;
 51  	}
 52  	word[j] = '\0';
 53  	return (word);
 54  }
 55  
 56  static char	**free_memory(char **words, size_t idx)
 57  {
 58  	size_t	i;
 59  
 60  	i = 0;
 61  	while (i <= idx)
 62  	{
 63  		free(words[i]);
 64  		words[i] = NULL;
 65  		i++;
 66  	}
 67  	free(words);
 68  	return (NULL);
 69  }
 70  
 71  static char	**make_words(char const *s, char **words, char c)
 72  {
 73  	size_t	i;
 74  	size_t	idx;
 75  
 76  	i = 0;
 77  	idx = 0;
 78  	while (s[i] != '\0')
 79  	{
 80  		while (s[i] != '\0' && s[i] == c)
 81  			i++;
 82  		if (s[i] != '\0' && s[i] != c)
 83  		{
 84  			words[idx] = add_word(s, c, i);
 85  			if (!words[idx])
 86  				return (free_memory(words, idx));
 87  			idx++;
 88  			while (s[i] != '\0' && s[i] != c)
 89  				i++;
 90  		}
 91  	}
 92  	words[idx] = NULL;
 93  	return (words);
 94  }
 95  
 96  char	**ft_split(char const *s, char c)
 97  {
 98  	char	**words;
 99  	size_t	count;
100  
101  	if (s == NULL)
102  		return (NULL);
103  	count = word_count(s, c);
104  	words = malloc(sizeof(char *) * (count + 1));
105  	if (!words)
106  		return (NULL);
107  	return (make_words(s, words, c));
108  }