How do I find the index of a character within a string in C?

bodacydo picture bodacydo · Jul 10, 2010 · Viewed 118.1k times · Source

Suppose I have a string "qwerty" and I wish to find the index position of the e character in it. (In this case the index would be 2)

How do I do it in C?

I found the strchr function but it returns a pointer to a character and not the index.

Answer

wj32 picture wj32 · Jul 10, 2010

Just subtract the string address from what strchr returns:

char *string = "qwerty";
char *e;
int index;

e = strchr(string, 'e');
index = (int)(e - string);

Note that the result is zero based, so in above example it will be 2.