C:strchr()和index()之间的区别
我正在用 C 语言做一些需要使用字符串的事情(就像大多数程序一样)。
查看手册页,我发现在 string(3) 处:
概要
#include
; char * 索引(const char *s, int c) (...) #include ; char * strchr(const char *s, int c)
所以我好奇地查看了 strchr(3) 和 index(3)...
我发现两者都执行以下操作:
strchr()/index()函数定位字符串中第一次出现的c s 所指向的。终止空字符被认为是 细绳;因此,如果 c 为“\0”,则函数将定位终止“\0”。
所以,手册页基本上是一个副本和内容。粘贴。
此外,我认为,由于某种混淆的必要性,第二个参数的类型为 int,但实际上是 char。我想我没有错,但是谁能向我解释一下为什么它是一个int
,而不是一个char
?
如果它们相同,那么哪个版本之间的兼容性更好,如果不同,那么区别是什么?
I am doing something in C which requires use of the strings (as most programs do).
Looking in the manpages, I found, at string(3):
SYNOPSIS
#include <strings.h> char * index(const char *s, int c) (...) #include <string.h> char * strchr(const char *s, int c)
So I curiously looked at both strchr(3) and index(3)...
And I found that both do the following:
The strchr()/index() function locates the first occurrence of c in the string
pointed to by s. The terminating null character is considered to be part of the
string; therefore if c is '\0', the functions locate the terminating '\0'.
So, the manpage is basically a copy & paste.
Besides, I suppose that, because of some obfuscated necessity, the second parameter has type int
, but is, in fact, a char
. I think I am not wrong, but can anyone explain to me why is it an int
, not a char
?
If they are both the same, which one is more compatible across versions, and if not, which's the difference?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
strchr()
是 C 标准库的一部分。index()
是现已弃用的 POSIX 函数。< /a> POSIX 规范建议将index()
实现为扩展为调用strchr()
的宏。由于
index()
在 POSIX 中已弃用,并且不属于 C 标准库的一部分,因此您应该使用strchr()
。第二个参数的类型为 int,因为这些函数早于函数原型。另请参阅 https://stackoverflow.com/a/5919802/ 了解更多信息。
strchr()
is part of the C standard library.index()
is a now deprecated POSIX function. The POSIX specification recommends implementingindex()
as a macro that expands to a call tostrchr()
.Since
index()
is deprecated in POSIX and not part of the C standard library, you should usestrchr()
.The second parameter is of type
int
because these functions predate function prototypes. See also https://stackoverflow.com/a/5919802/ for more information on this.看起来index()函数是一个较旧的函数,应该被strchr()替换。
请参阅http://www.opengroup.org/onlinepubs/000095399/functions/index。 html 他们建议用 strchr 替换索引并将索引标记为遗留函数。
It looks like the index() function is an older one that should be replaced by strchr().
See http://www.opengroup.org/onlinepubs/000095399/functions/index.html where they suggest to replace index by strchr and mark index as a legacy function.