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;
}
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.
thanks, eljobso
It simply subtracts str
, which is a pointer to the first character of the string, from the pointer to the found result.
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.