C: strchr() 和 index() 的区别

标签 c string standard-library

我正在用 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/

相关文章:

c - 从 Rust FFI 访问 DPDK 中的静态 C 函数

c++ - 使用 strlen 时不为空终止符添加 +1 会导致在使用 send 时发送额外的垃圾字节

c - 无法检查 Nt Authority\System SID

c - 如何在C中的二维数组中输入一个字符串?

c# - 使用 yield 生成给定长度的所有子字符串

c - 如何在 C 浮点型变量中存储 14.5 万亿和一些变化

ruby - 在 Ruby 中增加字符串的一部分

c++ - 在 C++ 中使用 'cin' 使数组与输入一样大

http - 使用 http.ServeFile 更改 HTTP 代码

c++ - 哪些常用的 C++ 环境缺乏对标准库的支持(即使不是全部,也是大部分)?