#include <stdlib.h>
#include <stdio.h>

void free_split(char **split);

int count_words(char *s)
{
    int i = 0;
    int wc = 0;

    while (s[i])
    {
        while (s[i] && (s[i] == ' ' || s[i] == '\n' || s[i] == '\t')) // attention ici ||
            i++;
        if (s[i])
            wc++;
        while (s[i] && (s[i] != ' ' && s[i] != '\n' && s[i] != '\t')) // attention ici &&
            i++;
    }
    return (wc);
}

char *ft_strncpy(char *dest, char *s, int n)
{
    int i = 0;

    while (i < n && s[i])
    {
        dest[i] = s[i];
        i++;
    }
    dest[i] = '\0';
    return (dest);
}

void free_split(char **split)
{
    int i = 0;

    while (split[i])
    {
        free(split[i]);
        i++;
    }
    free(split);
}

char **ft_split(char *s)
{
    int i = 0;
    int j = 0;
    int k = 0;
    int wc = count_words(s);
    char **out;

    out = (char **)malloc(sizeof(char *) * (wc + 1));
    if (out == NULL)
        return (NULL);

    while (s[i])
    {
        while (s[i] && (s[i] == ' ' || s[i] == '\n' || s[i] == '\t'))  // attention ici ||
            i++;
        j = i;
        while (s[i] && (s[i] != ' ' && s[i] != '\n' && s[i] != '\t')) // attention ici &&
            i++;
            i++;
        if (i > j)
        {
            out[k] = (char *)malloc(sizeof(char) * ((i - j) + 1));
            if (out[k] == NULL)
            {
                free_split(out);
                return (NULL);
            }
            ft_strncpy(out[k], &s[j], i - j);
            k++;
        }
    }
    out[k] = NULL;
    return (out);
}

int main(void)
{
    char *s = "  Salut belle blonde !";
    char **split = ft_split(s);
    int i = 0;

    if (!split)
    {
        printf("Erreur d'allocation mémoire!\n");
        return (1);
    }
    while (split[i])
    {
        printf("Mot %d: %s\n", i + 1, split[i]);
        free(split[i]);
        i++;
    }
    free(split);
    return (0);
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: