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 );
Just subtract the string address from what strchr returns: char *string = "qwerty"; char *e; int index; e = strchr(string, 'e'); index = (int)(e - string);
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.
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.
Functions cannot return C-style arrays. They can only modify them by reference or through pointers.
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 }
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");
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