我有C中strchr函数的示例代码。
/* strchr example */
#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;
}
问题是,我不明白,该程序如何计算外观人物的位置。
我认为这与“pch”和“str”的指针有关,但是这如何工作?
如果有人可以更详细地解释这一点,那就太好了。
谢谢,
Eljobso
最佳答案
它只是从指向找到结果的指针中减去str
,它是指向字符串第一个字符的指针。
然后,它成为从0索引的字符位置。这很容易理解,如果在字符串的第一个位置找到字符,则返回的指针将等于str
,因此(pstr - str) == 0
为true。添加一个使其基于1,这有时对于演示目的很有用。
关于c - C函数strchr-如何计算字符的位置?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13342959/