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
|
#include <string.h>
#include <stdlib.h>
char *str_replace (const char *txt, const char *Avant, const char *Apres)
{
const char *pos; /* Position d'une occurance de Avant dans txt */
char *TxtRetour; /* La chaine retournée */
size_t PosTxtRetour; /* Position du prochain caractère à écrire */
/* dans TxtRetour */
size_t Long; /* Long d'une chaine à écrire dans TxtRetour */
size_t TailleAllouee; /* Taille allouée à TxtRetour */
/* Cherche la première occurence */
pos = strstr (txt, Avant);
/* Aucune occurrences : renvoie simplement une copie de la chaine */
if (pos == NULL)
{
return NULL;
}
/* Alloue une nouvelle chaine */
Long = (size_t)pos - (size_t)txt;
TailleAllouee = Long + strlen (Apres) + 1;
TxtRetour = malloc (TailleAllouee);
PosTxtRetour = 0;
/* Copie la première partie de la chaîne sans occurrence */
strncpy (TxtRetour + PosTxtRetour, txt, Long);
PosTxtRetour += Long;
txt = pos + strlen (Avant);
/* Ajoute la chaîne de remplacement Apres */
Long = strlen (Apres);
strncpy (TxtRetour + PosTxtRetour, Apres, Long);
PosTxtRetour += Long;
/* Cherche la prochaine occurrence */
pos = strstr (txt, Avant);
while (pos != NULL)
{
/* Agrandit la chaine */
Long = (size_t)pos - (size_t)txt;
TailleAllouee += Long + strlen (Apres);
TxtRetour = (char *)realloc (TxtRetour, TailleAllouee);
/* Copie ce qu'il y a entre la dernier occurrence et la nouvelle */
strncpy (TxtRetour + PosTxtRetour, txt, Long);
PosTxtRetour += Long;
/* Passe l'occurrence */
txt = pos + strlen (Avant);
/* Ajoute la chaîne de remplacement */
Long = strlen (Apres);
strncpy (TxtRetour + PosTxtRetour, Apres, Long);
PosTxtRetour += Long;
/* Cherche la prochaine occurrence */
pos = strstr (txt, Avant);
}
/* Ajoute le reste de la chaîne (il reste au moins '\0') */
Long = strlen (txt) + 1;
TailleAllouee += Long;
TxtRetour = realloc (TxtRetour, TailleAllouee);
strncpy (TxtRetour + PosTxtRetour, txt, Long);
return TxtRetour;
} |
Partager