[英]Is there a function in c that will return the index of a char in a char array?
c中是否有一个函数可以返回char数组中char的索引?
例如:
char values[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char find = 'E';
int index = findIndexOf( 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 <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;
}
strpos怎么样?
#include <string.h>
int index;
...
index = strpos(values, find);
请注意,strpos需要一个以零结尾的字符串,这意味着您应该在末尾添加一个'\\ 0'。 如果你不能这样做,你就会留下手动循环和搜索。
您可以使用strchr获取指向第一个匹配项的指针,并从原始char *中减去(如果不为null)以获取位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.