且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

c中是否有一个函数可以返回char数组中char的索引?

更新时间:2023-02-19 11:43:05

strchr 返回指向第一次出现的指针,所以要找到索引,只需取起始指针的偏移量即可.例如:

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
}