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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* -tc- Duplique une sous-chaine de longueur len */
static char *
str_n_dup(char const *s, size_t len)
{
char *ret = NULL;
if (s != NULL && len > 0)
{
ret = malloc((len + 1) * sizeof *ret);
if (ret != NULL)
{
ret[0] = 0;
strncat(ret, s, len);
}
}
return ret;
}
/* -tc- Compte le nombre d'occurences d'un caractere dans une chaine */
static size_t
s_count_chr(char const *s, char c)
{
size_t ret = 0;
if (s != NULL)
{
size_t i;
while (s[i] != 0)
{
if (s[i++] == c)
{
ret++;
}
}
}
return ret;
}
static char **
s_split(char *s, char delim)
{
char **tab = NULL;
size_t count = 1;
if (s != NULL)
{
size_t count = s_count_chr(s, delim) + 1;
tab = malloc((count + 1) * sizeof *tab);
if (tab != NULL)
{
char *debut = s;
char *fin = NULL;
size_t i = 0;
while ((fin = strchr(debut, delim)) != NULL)
{
tab[i++] = str_n_dup(debut, fin - debut);
debut = fin + 1;
}
tab[i++] = str_n_dup(debut, strlen(debut));
tab[i] = NULL;
}
}
return tab;
}
static void
s_split_tab_free(char **pp)
{
if (pp != NULL)
{
size_t i = 0;
while (pp[i] != NULL)
{
free(pp[i++]);
}
free(pp);
}
}
static void
s_split_tab_display(char **pp)
{
if (pp != NULL)
{
size_t i = 0;
while (pp[i] != NULL)
{
puts(pp[i++]);
}
}
}
int main(void)
{
char ligne[] = "mot1,mot2,mot3,mot4,mot5,mot6";
char **tab = s_split(ligne, ',');
if (tab != NULL)
{
s_split_tab_display(tab);
s_split_tab_free(tab), tab = NULL;
}
return 0;
} |
Partager