tags:

views:

108

answers:

3

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

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

Please help me out!

Thanks, Boda Cydo.

+4  A: 

Just subtract the string address from what strchr returns:

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

e = strchr(string, 'e');
index = (int)(e - string);
wj32
down-voter: Is there anything wrong with the code?
wj32
Thanks, i tried and it worked!
bodacydo
This is "right" but theoretically scary in that there's nothing in the standard stopping the length of a string from vastly exceeding the capacity of a plain 'int'. If you can depend on C99, use uintptr_t (defined in stdint.h) for this. It should also eliminate the need for that cast.
Nicholas Knight
Result of pointer difference is ptrdiff_t.
Nyan
Yes, that's true. However I thought at least for a beginner example an int would be much clearer, and I am certain that the OP is not dealing with 5 GB strings.
wj32
`size_t` is probably the clearest one to use, since it's big enough to hold the length of any object (and thus any string). The *real* issue with this code is that you should have `if (e) { } else { }` to handle the case when the character is not found within the string.
caf
Hmmm. That is a good point.
wj32
@wj32: Just for beginners it is important to learn to use the correct types. Most of the times (99%, I guess) `int` is wrong, and all these *beginner* examples just teach them the wrong attitude.
Jens Gustedt
+2  A: 
void myFunc(char* str, char c)
{
    char* ptr;
    int index;

    ptr = strchr(str, c);
    if (ptr == NULL)
    {
        printf("Character not found\n");
        return;
    }

    index = ptr - str;

    printf("The index is %d\n", index);
    ASSERT(str[index] == c);  // Verify that the character at index is the one we want.
}

This code is currently untested, but it demonstrates the proper concept.

abelenky
+1  A: 

You can also use strcspn(string, "e") but this may be much slower since it's able to handle searching for multiple possible characters. Using strchr and subtracting the pointer is the best way.

R..