Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.indexOf function in C

Tags:

c

string

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.

like image 736
Ryan Ahearn Avatar asked Aug 07 '08 15:08

Ryan Ahearn


People also ask

What does indexOf do in C?

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.

What is string indexOf?

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.

Can we index string in C?

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.


2 Answers

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" */ } 
like image 52
Bill Avatar answered Sep 22 '22 11:09

Bill


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; } 
like image 42
Jonathan Works Avatar answered Sep 20 '22 11:09

Jonathan Works