Josh Curren
Josh Curren

Reputation: 10226

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

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

Upvotes: 28

Views: 89311

Answers (7)

moonasteroid
moonasteroid

Reputation: 65

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;
}

Upvotes: 1

null
null

Reputation: 11849

Safe index_of() function that works even when it finds nothing (returns -1 in such case).

#include <stddef.h>
#include <string.h>
ptrdiff_t index_of(const char *string, char search) {
    const char *moved_string = strchr(string, search);
    /* If not null, return the difference. */
    if (moved_string) {
        return moved_string - string;
    }
    /* Character not found. */
    return -1;
}

Upvotes: 3

John Bode
John Bode

Reputation: 123448

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

Upvotes: 9

Ed Swangren
Ed Swangren

Reputation: 124642

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.

Upvotes: 0

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143081

int index = strchr(values,find)-values;

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

Upvotes: 5

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391326

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.

Upvotes: 1

Jesse Beder
Jesse Beder

Reputation: 34034

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
}

Upvotes: 57

Related Questions