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
| char **strsplit(const char *s, const char sep){
if(s==NULL)
return NULL;
int nbsep=0; /* nb de séparateurs */
int j;
for( j=0;s[j]!='\0';j++){
if (s[j]==sep)
nbsep++;
}
//printf("nbsep = %d\n",nbsep);
char **res=malloc((nbsep+2)*sizeof(char*)); /* allocation du résultat */
int n=0;
int i=0;
int APRESSEP=0; /* faux */
do{
int l=0;
// lng de la sous-chaîne
while(s[i]!='\0' && s[i]!=sep){
l++;
i++;
}
res[n]=malloc(l+1); // je ne comprend pas ce que malloc fait ici (res[n] est un tableau ?)
strncpy(res[n], s+i-l, l);
res[n][l]='\0'; // res[n][l] sa signifie quoi svp
n++;
APRESSEP=0;
if(s[i]==sep){
i++;
APRESSEP=1;
}
} while(s[i]!='\0');
if(APRESSEP){ /* sep suivi de fin de chaîne */
//printf("n=%d ; i=%d\n",n,i);
res[n]=malloc(1);
res[n][0]='\0';
n++;
}
res[n]=NULL;
return res;
} |
Partager