Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a function in c that will return the index of a char in a char array?

Tags:

Is there a function in c that will return the index of a char in a char array?

For example something like:

char values[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; char find = 'E';  int index = findIndexOf( values, find ); 
like image 268
Josh Curren Avatar asked Sep 25 '09 20:09

Josh Curren


People also ask

How do you find the index of a char in a string in C?

Just subtract the string address from what strchr returns: char *string = "qwerty"; char *e; int index; e = strchr(string, 'e'); index = (int)(e - string);

How do you find the index of an element in a char array?

getChar() is an inbuilt method in Java and is used to return the element present at a given index from the specified Array as a char.

Can you return a char array in C?

C programming does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index.

Can a function return a char array?

Functions cannot return C-style arrays. They can only modify them by reference or through pointers.


2 Answers

strchr returns the pointer to the first occurrence, so to find the index, just take the offset with the starting pointer. For example:

char values[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; char find = 'E';  const char *ptr = strchr(values, find); if(ptr) {    int index = ptr - values;    // do something } 
like image 165
Jesse Beder Avatar answered Oct 06 '22 19:10

Jesse Beder


There's also size_t strcspn(const char *str, const char *set); it returns the index of the first occurence of the character in s that is included in set:

size_t index = strcspn(values, "E"); 
like image 28
John Bode Avatar answered Oct 06 '22 19:10

John Bode