libft / ft_split.c 109 commits
14-04-2026
82 lines 1.8 kB
 1/* ************************************************************************** */
 2/*                                                                            */
 3/*                                                        :::      ::::::::   */
 4/*   ft_split.c                                         :+:      :+:    :+:   */
 5/*                                                    +:+ +:+         +:+     */
 6/*   By: mleitao <mleitao@student.42.fr>            +#+  +:+       +#+        */
 7/*                                                +#+#+#+#+#+   +#+           */
 8/*   Created: 2026/03/13 18:34:00 by mleitao           #+#    #+#             */
 9/*   Updated: 2026/04/14 19:21:43 by mleitao          ###   ########.fr       */
10/*                                                                            */
11/* ************************************************************************** */
12
13#include "libft.h"
14#include <stdlib.h>
15
16static size_t	count_words(const char *s, char c)
17{
18	size_t	w;
19
20	w = 0;
21	while (*s)
22	{
23		while (*s == c)
24			s++;
25		if (*s)
26			w++;
27		while (*s && *s != c)
28			s++;
29	}
30	return (w);
31}
32
33static const char	*start_word(const char *s, char c)
34{
35	while (*s == c)
36		s++;
37	return (s);
38}
39
40static void	*free_all(char **r)
41{
42	char	**p;
43
44	p = r;
45	while (*p)
46		free(*p++);
47	free(r);
48	return (NULL);
49}
50
51static char	**split(char **r, char const *s, char c)
52{
53	const char	*ss;
54	char		**p;
55
56	p = r;
57	while (*s)
58	{
59		s = start_word(s, c);
60		if (!*s)
61			break ;
62		ss = s;
63		while (*s && *s != c)
64			s++;
65		*p = ft_substr(ss, 0, s - ss);
66		if (!*p)
67			return (free_all(r));
68		p++;
69	}
70	return (r);
71}
72
73char	**ft_split(char const *s, char c)
74{
75	char	**r;
76
77	r = ft_calloc(count_words(s, c) + 1, sizeof(char *));
78	if (!r)
79		return (NULL);
80	r = split(r, s, c);
81	return (r);
82}