gpt4 book ai didi

c - strchr(), 这如何正确地找到一个字符的索引

转载 作者:太空宇宙 更新时间:2023-11-04 08:53:33 24 4
gpt4 key购买 nike

我正在查看 strchr() 的示例:http://www.cplusplus.com/reference/cstring/strchr/

为什么这样可以正确找到索引?直觉上它看起来应该给出负索引:

#include <stdio.h>
#include <string.h>

int main ()
{
char str[] = "This is a sample string";
char * pch;
printf ("Looking for the 's' character in \"%s\"...\n",str);
pch=strchr(str,'s');
while (pch!=NULL)
{
printf ("found at %d\n",pch-str+1);
pch=strchr(pch+1,'s');
}
return 0;
}

最佳答案

Intuitively it looks like it should be giving a negative index:

不,因为 strchr 返回一个指向该字符所在位置的指针。因此,每次 strchr 返回非 NULL 时,该指针都会比它开始的指针“更靠下”。

关于c - strchr(), 这如何正确地找到一个字符的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18578945/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com