views:

328

answers:

6

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 = findInedexOf( values, find );
+5  A: 

strchr()

chaos
Does not answer the question, though it is a part of the answer.
Ed Swangren
+11  A: 

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
}
Jesse Beder
A: 

What about strpos?

#include <string.h>

int index;
...
index = strpos(values, find);

Note that strpos expects a zero-terminated string, which means you should add a '\0' at the end. If you can't do that, you're left with a manual loop and search.

Lasse V. Karlsen
I don't think that exists in the C standard library, though I could be wrong.
Ed Swangren
Personally I have more confidence in the strchr answers, I'd really like one of those be marked as the answer instead. I only found one really old piece of source code using that function, and I don't know how standard it is when I consider it.
Lasse V. Karlsen
strpos() is not a standard C (or even C++) function. Quite common in PHP, etc...
jesup
Odd, but I do have a piece of C code that uses it. But as I said, I don't know how standard it is.
Lasse V. Karlsen
strpos isn't part of the C std lib - but it is probably present on most systems.
Martin Beckett
after looking through some other code I have found some c that uses strpos()
Josh Curren
A: 
int index = strchr(values,find)-values;

Note, that if there's no find found, then strchr returns NULL, so index will be negative.

Michael Krelin - hacker
A: 

You can use strchr to get a pointer to the first occurrence and the subtract that (if not null) from the original char* to get the position.

Ed Swangren
A: 

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");
John Bode