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.
IndexOf(char x, int start1) method. This method returns the zero-based index of the first occurrence of the specified character within the string. However, the searching of that character will start from a specified position and if not found it returns -1.
Java String indexOf() Method The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.
The index() function locates the first occurrence of c (converted to an unsigned char) in the string pointed to by string. The character c can be the NULL character (\0); the ending NULL is included in the search. The string argument to the function must contain a NULL character (\0) marking the end of the string.
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" */ } 
                        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; } 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With