C函数和strchr - 如何计算字符的位置? [英] C function strchr - How to calculate the position of the character?
问题描述
我有这样的例子code在C strchr函数。
I have this example code for the strchr function in C.
/* 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和海峡的三分球,但这是如何工作的?
The problem is, I don't understand, how this program calculates the position of the looking character. I think it has something to do with the pointers of "pch" and "str", but how does this work?
将是巨大的,如果有别人谁能够在更详细一点解释。
结果
Would be great, if there is somebody who could explain this in little more detail.
谢谢,
eljobso
thanks, eljobso
推荐答案
它只是减去 STR
,这是一个指向字符串的第一个字符,从指针对发现的结果。
It simply subtracts str
, which is a pointer to the first character of the string, from the pointer to the found result.
这便成为字符的位置,从0收录这很容易理解,如果角色在字符串的第一个位置找到,返回的指针将等于 STR
,从而(PSTR - STR)== 0
是真实的。增加一个使1为主,这有时是presentational目的。
This then becomes the position of the character, indexed from 0. This is easy to understand, if the character is found in the first position of the string, the returned pointer will be equal to str
, and thus (pstr - str) == 0
is true. Adding one makes it 1-based, which is sometimes useful for presentational purposes.
这篇关于C函数和strchr - 如何计算字符的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!