String.indexOf function in C

前端 未结 7 1389
Happy的楠姐
Happy的楠姐 2020-11-30 06:41

Is there a C library function that will return the index of a character in a string?

So far, all I\'ve found are functions like strstr that will return the found cha

7条回答
  •  悲哀的现实
    2020-11-30 06:49

    strstr returns a pointer to the found character, so you could use pointer arithmetic: (Note: this code not tested for its ability to compile, it's one step away from pseudocode.)

    char * source = "test string";         /* assume source address is */
                                           /* 0x10 for example */
    char * found = strstr( source, "in" ); /* should return 0x18 */
    if (found != NULL)                     /* strstr returns NULL if item not found */
    {
      int index = found - source;          /* index is 8 */
                                           /* source[8] gets you "i" */
    }
    

提交回复
热议问题