简体   繁体   中英

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

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
}
int index = strchr(values,find)-values;

注意,如果find ,则strchr返回NULL ,因此index将为负数。

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

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

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.

您可以使用strchr获取指向第一个匹配项的指针,并从原始char *中减去(如果不为null)以获取位置。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM