#include <stdio.h>
#include <stdlib.h>
int count_w(char *s)
{
int wc = 0;
int in_word = 0; // Indicateur si on est dans un mot
while (*s)
{
if (*s == '\n' || *s == ' ' || *s == '\t')
in_word = 0; // Sortie du mot
else if (in_word == 0) // Début d'un nouveau mot
{
in_word = 1;
wc++;
}
s++;
}
return wc;
}
char *copy_w(char *src, int n)
{
char *word = malloc(sizeof(char) * (n + 1));
if (word == NULL)
return NULL;
int i = 0;
while (src[i] && i < n)
{
word[i] = src[i];
i++;
}
word[i] = '\0';
printf("le resultat word est: %s \n", word);
return word;
}
void free_split(char **split)
{
int i = 0;
if (split == NULL)
return;
while (split[i])
{
free(split[i]);
i++;
}
free(split);
}
char **ft_split(char *str)
{
int i = 0;
int start = 0;
int wc = 0;
int k = 0;
char **out;
wc = count_w(str);
printf("La valeur de WC est: %d \n", wc);
out = malloc(sizeof(char *) * (wc + 1)); // +1 pour NULL final, ne pas oublier de mettre (char *) car c est un ptr vers une string
if (out == NULL) // toujour vérifier l allocation apres malloc!!!
return NULL;
while (str[i]) // tant que pas a la fin!
{
// Ignorer les espaces initiaux
while (str[i] && (str[i] == '\n' || str[i] == ' ' || str[i] == '\t')) // ou car ne peut pas etre espace et saut a la fois (soit l un soit l autre, d ou le ou)
i++;
start = i; // start index du premier caractere du mot
while (str[i] && (str[i] != '\n' && str[i] != ' ' && str[i] != '\t')) // ensuite continuer dans le mot, avancer tant que pas blanc, ici si on est a la fin sur 0 alors n avance pas le i donc i = start alors n ecrit pas de nouveau mot
i++;
if (i > start) // S'assurer qu'on ne stocke que des mots (au moins un caractère)
{
out[k] = copy_w(&str[start], i - start); // copier le mot dans out, donne l & de str depuis start, et donne la longueur
if (out[k] == NULL) // comme copy_w utilise malloc il faut vérifier le retour si ptr valide
{
free_split(out); // si pas valide alors on effece tout ce qu on a malloc et quitte la fonction!
return NULL;
}
}
k++; // sinon on a écrit un mot on passe au mot suivant (voir si au bon endroit ce k++)
}
out[k] = NULL; // Assurer la terminaison correcte du tableau
return (out);
}
int main()
{
int i = 0;
char *str = "Je lis ! ";
char **split;
split = ft_split(str);
if (split == NULL)
{
printf("Erreur d'allocation mémoire.\n");
return 1;
}
while (split[i])
{
printf("Réultat: %s\n", split[i]);
i++;
}
free_split(split);
return 0;
}
To embed this project on your website, copy the following code and paste it into your website's HTML: