Question

String.indexOf function in C

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 char *, not it's location in the original string.

 47  108879  47
1 Jan 1970

Solution

 39

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" */
}
2008-08-07

Solution

 16

I think that

size_t strcspn ( const char * str1, const char * str2 );

is what you want. Here is an example pulled from here:

/* strcspn example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] = "fcba73";
  char keys[] = "1234567890";
  int i;
  i = strcspn (str,keys);
  printf ("The first number in str is at position %d.\n",i+1);
  return 0;
}
2008-08-07