我正在用 C 语言做一些需要使用字符串的事情(就像大多数程序一样)。
查看联机帮助页,我发现在 string(3) 处:
SYNOPSIS
#include <strings.h> char * index(const char *s, int c) (...) #include <string.h> char * strchr(const char *s, int c)
于是我好奇的看了strchr(3)和index(3)这两个...
我发现两者都执行以下操作:
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'.
因此,联机帮助页基本上是复制和粘贴。
此外,我想,由于某些混淆的必要性,第二个参数的类型为 int
,但实际上是一个 char
。我想我没有错,但是谁能给我解释一下为什么它是 int
,而不是 char
?
如果两者相同,哪个版本的兼容性更好,如果不同,有什么区别?
最佳答案
strchr()
是 C 标准库的一部分。 index()
是 a now deprecated POSIX function. POSIX 规范建议将 index()
实现为扩展为调用 strchr()
的宏。
由于 index()
在 POSIX 中被弃用并且不是 C 标准库的一部分,因此您应该使用 strchr()
。
第二个参数是 int
类型,因为这些函数早于函数原型(prototype)。另见 https://stackoverflow.com/a/5919802/有关这方面的更多信息。
关于C: strchr() 和 index() 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4091864/