这有点奇怪。
我写了一个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;
}
我已经对它进行了一些测试,但是 你看到它有什么缺陷吗?安全问题左右?任何增强功能?可以改进吗? 更重要的是:这是一个坏主意吗?
一些用法。
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;
}
答案 0 :(得分:5)
编辑效果更好,但界面仍然令人惊讶。我将begin
参数(被搜索的 haystack )作为第一个参数c
参数
(搜索 needle )第二个,from
参数(搜索的开始位置)第三个。这个顺序在相当大的API集中似乎是惯用的。
答案 1 :(得分:2)
代码有一个深奥的接口 - 传入指向字符串最后一个字符的指针和字符串的长度。这将导致使用它的问题。
(或者,代码有一个错误 - 你应该在循环之前向s添加计数。)
答案 2 :(得分:1)
如果begin是from,则当前代码将始终返回begin,这不是您想要的。循环后的代码只能返回NULL。而不是开始!=从循环条件,我会使用开始&lt;否则,当有人混淆参数的顺序时,你会指针算术溢出。
编辑:第二个想法,因为你想要[开始,从]包含它应该开始&lt; = from
答案 3 :(得分:1)
我写了一个C函数。它的'喜欢'strchr / strrchr。
您试图重新发明strrchr()
,因此它不像strchr()
。
你看到它有任何缺陷吗?
是。一些。 : - (
由于b_strchr()
可以返回NULL
,因此您不应将其直接放入printf()
语句中。引用NULL
通常会导致段错误。
你可能会对自己最喜欢的......的变化感觉更好。
char *result;
result = b_strchr(string + 9, 'a', 10));
if (result == NULL)
{
printf("c: NULL\n");
}
else
{
printf("c: %c\n", *result);
}
此外,
时(count >= length of the input string) and the character is not found
你将得到不可预测的结果,因为s
不再指向字符串中的字符 - s
指向字符串开头之前的内存。举个例子,试试
result = b_strchr(string + 9, 'a', 11));
if (result == NULL)
{
printf("c: NULL\n");
}
else
{
printf("c: %c\n", *result);
}
看看会发生什么。
扩展您的使用测试用例,以包括您知道将成功运行的条件之外的条件。请其他人帮助您设计真正测试代码的测试用例。
更重要的是:这是个坏主意吗?
作为一项学习练习,绝对不是。
但是,在这种情况下,对于生产代码,您最好坚持使用标准strrchr()
。