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

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

例如:

char values[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; char find = 'E'; int index = findInedexOf( values, find ); 

strchr返回指向第一个匹配项的指针,因此要查找索引,只需使用起始指针获取偏移量。 例如:

 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将为负数。

还有size_t strcspn(const char *str, const char *set) ; 它返回包含在set中的s中第一个出现的字符的索引:

 size_t index = strcspn(values, "E"); 

安全的index_of()函数即使没有找到也能工作(在这种情况下返回-1 )。

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

strpos怎么样?

 #include  int index; ... index = strpos(values, find); 

请注意,strpos期望一个以零结尾的字符串,这意味着您应该在末尾添加一个’\ 0’。 如果你不能这样做,你就会留下手动循环和搜索。

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