bodacydo
bodacydo

Reputation: 79319

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

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.

Upvotes: 59

Views: 175211

Answers (5)

Varun Narayanan
Varun Narayanan

Reputation: 343

This should do it:

//Returns the index of the first occurence of char c in char* string. If not found -1 is returned.
int get_index(char* string, char c) {
    char *e = strchr(string, c);
    if (e == NULL) {
        return -1;
    }
    return (int)(e - string);
}

Upvotes: 3

wj32
wj32

Reputation: 8403

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.

Upvotes: 117

Dan Molik
Dan Molik

Reputation: 11

What about:

char *string = "qwerty";
char *e = string;
int idx = 0;
while (*e++ != 'e') idx++;

copying to e to preserve the original string, I suppose if you don't care you could just operate over *string

Upvotes: 1

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215211

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.

Upvotes: 8

abelenky
abelenky

Reputation: 64682

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.

Upvotes: 5

Related Questions