Is there a function in c that will return the index of a char in a char array?

Viewed 83084

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 );
7 Answers

You can use strcspn() to get the index of a char in a string, or use my lousy implementation:

// Returns the index of the first occurrence of a char
int string_indexof(char ch, char *everything) {
    int everythingLength = strlen(everything);
    for (int i = 0; i < everythingLength; i++) {
        if (ch == everything[i]) {
            return i;
        }
    }

    return -1;
}
Related