C function strchr - How to calculate the position of the character?

烂漫一生 提交于 2019-12-11 03:07:40

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/13342959/c-function-strchr-how-to-calculate-the-position-of-the-character

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!