这是一个有点奇怪的问题。
我写了一个 C 函数。它的'喜欢' strchr / strrchr。它应该在 c 字符串中查找一个字符,但要向后查找,并返回一个指向它的指针。由于 c 字符串不是“null 启动”,它还需要第三个参数“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;
}