c'est une question plutôt étrange.Cette fonction peut-elle être plus sûre? Vous cherchez des conseils et vos pensées!
J'ai écrit une fonction C. C'est «comme» strchr/strrchr. Il est supposé chercher un personnage dans un c-string, mais revenir en arrière, et lui renvoyer un pointeur. Comme les chaînes c ne sont pas "nulles", il faut aussi un troisième paramètre "count", indiquant le nombre de caractères qu'il doit regarder en arrière.
/*
*s: Position from where to start looking for the desired character.
*c: Character to look for.
*count: Amount of tests to be done
*
* Returns NULL if c is not in (s-count,s)
* Returns a pointer to the occurrence of c in s.
*/
char* b_strchr(const char* s,int c,size_t count){
while (count-->0){
if (*s==c) return s;
s--;
}
return NULL;
}
Je l'ai fait des tests sur, mais Voyez-vous des défauts en elle? Problèmes de sécurité ou autre? Des améliorations? Pourrait-il être amélioré? Et plus important: est-ce une mauvaise idée?
Certains usages.
char* string = "1234567890";
printf("c: %c\n",*b_strchr(string+9,'5',10));//prints 5
printf("c: %c\n",*b_strchr(string+6,'1',7));//prints 1
EDIT: Nouvelle interface, quelques modifications.
/*
* from: Pointer to character where to start going back.
* begin: Pointer to characther where search will end.
*
* Returns NULL if c is not between [begin,from]
* Otherwise, returns pointer to c.
*/
char* b_strchr(const char* begin,int c,const char* from){
while (begin<=from){
if (*from==c) return from;
from--;
}
return NULL;
}
Merci! Je n'avais pas pensé à ça. – Tom