D'après mon post précédent, j'ai trouvé le code suivant. Je suis sûr qu'il y a une meilleure façon de le faire. Je me demande, qu'est-ce que ce serait?c - manipulation de chaîne pour le membre struct
Il divise la chaîne si le nombre maximal de caractères est OR
si @ est trouvé. Toute idée serait appréciée!
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct my_struct {
char *str;
};
int main() {
struct my_struct *struc;
int max = 5;
char *tmp = "Hello [email protected] Bar In [email protected] Foo dot [email protected]@there";
struc = malloc (20 * sizeof (struct my_struct));
int strIdx = 0, offSet = 0;
char *p = tmp;
char *tmpChar = malloc (strlen (tmp) + 1), *save;
save = tmpChar;
while (*p != '\0') {
if (offSet < max) {
offSet++;
if (*p == '@') {
if (offSet != 1) {
*tmpChar = '\0';
struc[strIdx++].str = strndup (save, max);
save = tmpChar;
}
offSet = 0;
} else
*tmpChar++ = *p;
} else { // max
offSet = 0;
*tmpChar = '\0';
struc[strIdx++].str = strndup (save, max);
save = tmpChar;
continue;
}
p++;
}
struc[strIdx++].str = strndup (save, max); // last 'save'
for (strIdx = 0; strIdx < 11; strIdx++)
printf ("%s\n", struc[strIdx].str);
for (strIdx = 0; strIdx < 11; strIdx++)
free (struc[strIdx].str);
free (struc);
return 0;
}
Sortie à 5 caractères max:
Hello
Worl
d
Foo B
ar In
here
Bar F
oo do
t com
here
there
Un commentaire (comme un commentaire): les noms comme 'i',' j', 'p',' c', 'ss' et' s' ne facilitent pas la lecture du code. Si 'j' est vraiment' offset', appelez ça. Il semble que 'i' est un index dans votre tableau de structures. 'string_idx',' strIdx', ou même 'idx' seraient plus significatifs. – nmichaels
@Nathon: Merci pour l'observation, je l'ai rendu un peu plus lisible :) – Mike