这有点奇怪的问题.
我写了一个C函数.它的'喜欢'strchr/strrchr.它应该在c字符串中查找一个字符,但是向后移动,并返回指向它的指针.由于c字符串不是"空启动",它还需要第三个参数'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;
}
Run Code Online (Sandbox Code Playgroud)
我已经对它进行了一些测试,但是你看到它有什么缺陷吗?安全问题左右?任何增强功能?可以改进吗?更重要的是:这是一个坏主意吗?
一些用法.
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
Run Code Online (Sandbox Code Playgroud)
/*
* 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;
}
Run Code Online (Sandbox Code Playgroud)
编辑效果更好,但界面仍然令人惊讶.我将begin参数(被搜索的草堆)作为第一个参数,c参数(被搜索的针)第二个,from参数(搜索的开始位置)第三个.在相当大的API集中,该顺序似乎是惯用的.