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
| // nombre d'occurrences de substring dans txt
// retourner -1 si substring est une chaîne vide
int str_count(const char *txt, const char *substring)
{
// ...
}
// remplacer toutes les occurrences de Avant par Apres dans la chaine txt
// retourner false en cas d'erreur
bool str_replace_without_alloc(char *Resultat, size_t tailleMaxResultat, const char *txt, const char *Avant, const char *Apres)
{
assert(Resultat != txt);
// ...
}
char *str_replace(const char *txt, const char *Avant, const char *Apres)
{
char* TxtRetour = NULL;
assert(strlen(Avant) > 0);
if(strlen(Avant) == 0)
return TxtRetour;
const int N = str_count(txt, Avant);
if(N <= 0)
return TxtRetour;
const size_t tailleTxtRetour = strlen(txt) - N*strlen(Avant) + N*strlen(Apres);
TxtRetour = (char *) malloc(tailleTxtRetour + 1);
if(TxtRetour == NULL)
return TxtRetour;
if(!str_replace_without_alloc(TxtRetour, tailleTxtRetour, txt, Avant, Apres)) {
free(TxtRetour);
TxtRetour = NULL;
}
return TxtRetour;
} |
Partager