这个问题有点奇怪。
我写了一个 C 函数。它“像”strchr/strrchr。它应该在 C 字符串中寻找一个字符,但向后查找,并返回指向它的指针。由于 c 字符串不是“null initiated”,它还需要第三个参数“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;
}
最佳答案
经过编辑更好,但界面仍然令人惊讶。我将 begin
参数(正在搜索的 haystack)作为第一个参数,c
参数
(正在搜索的 needle)第二,from
参数(搜索的起始位置)第三。在相当大的一组 API 中,该顺序似乎是惯用的。
关于这个功能可以更安全吗?寻找提示和您的想法!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1077479/