これは少し奇妙な質問です。
C関数を書きました。その「のような」strchr/strrchr。c文字列内の文字を検索することになっていますが、逆方向に移動して、その文字へのポインタを返します。c文字列は「nullで開始」されないため、3番目のパラメータ「count」も取ります。これは、逆方向に見る必要のある文字数を示します。
/*
*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;
}
私はそれについていくつかのテストをしました、しかしあなたはそれに何か欠陥を見ますか?セキュリティの問題かそこら?何か機能強化はありますか?改善できますか?そしてもっと重要なのは、これは悪い考えですか?
いくつかの使用法。
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
編集:新しいインターフェース、いくつかの変更。
/*
* 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;
}