aboutsummaryrefslogtreecommitdiff
path: root/exam_final/rendu/ft_split/ft_split.c
blob: 75d9f8d12b578afda882fffacd9617bca8b5e15c (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
68
69
70
71
72
73
74
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   ft_split.c                                         :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: exam <marvin@42.fr>                        +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2019/07/26 12:35:48 by exam              #+#    #+#             */
/*   Updated: 2019/07/26 13:09:10 by exam             ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include <stdlib.h>

int		in_charset(char c)
{
	return (c == ' ' || c == '\n' || c == '\t');
}

int		count_segment(char *str)
{
	int	counter;

	counter = 0;
	while (*str)
	{
		if (in_charset(*str))
		{
			str++;
			continue ;
		}
		counter++;
		while (*str && !in_charset(*str))
			str++;
	}
	return (counter);
}

char    **ft_split(char *str)
{
	char	**strs;
	char	*tmp;
	int		size;
	int		i;
	int		j;

	size = count_segment(str);
	if ((strs = (char**)malloc(sizeof(char*) * (size + 1))) == NULL)
		return (NULL);
	i = 0;
	while (i < size)
	{
		if (*str && in_charset(*str))
		{
			str++;
			continue ;
		}
		j = 0;
		while (str[j] && !in_charset(str[j]))
			j++;
		if ((tmp = (char*)malloc(sizeof(char) * (j + 1))) == NULL)
			return (NULL);
		j = 0;
		while (*str && !in_charset(*str))
		{
			tmp[j] = *str++;
			j++;
		}
		tmp[j] = '\0';
		strs[i++] = tmp;
	}
	strs[i] = NULL;
	return (strs);
}