【发布时间】:2011-03-14 03:45:16
【问题描述】:
假设我有一个字符串"qwerty",我希望在其中找到e 字符的索引位置。 (在这种情况下,索引为2)
我如何在 C 中做到这一点?
我找到了strchr 函数,但它返回一个指向字符而不是索引的指针。
【问题讨论】:
-
String.indexOf function in C 的可能重复项
假设我有一个字符串"qwerty",我希望在其中找到e 字符的索引位置。 (在这种情况下,索引为2)
我如何在 C 中做到这一点?
我找到了strchr 函数,但它返回一个指向字符而不是索引的指针。
【问题讨论】:
只需从 strchr 返回的内容中减去字符串地址即可:
char *string = "qwerty";
char *e;
int index;
e = strchr(string, 'e');
index = (int)(e - string);
请注意,结果是从零开始的,所以在上面的例子中,它将是 2。
【讨论】:
size_t 可能是最清晰的使用方法,因为它大到足以容纳任何对象(以及任何字符串)的长度。此代码的真正 问题是您应该有if (e) { } else { } 来处理在字符串中找不到字符的情况。
int 是错误的,所有这些 初学者 的例子只是教会了他们错误的态度。
C 编译器?
您也可以使用strcspn(string, "e"),但这可能会慢得多,因为它能够处理搜索多个可能的字符。使用strchr并减去指针是最好的方法。
【讨论】:
void myFunc(char* str, char c)
{
char* ptr;
int index;
ptr = strchr(str, c);
if (ptr == NULL)
{
printf("Character not found\n");
return;
}
index = ptr - str;
printf("The index is %d\n", index);
ASSERT(str[index] == c); // Verify that the character at index is the one we want.
}
此代码目前未经测试,但它展示了正确的概念。
【讨论】:
应该这样做:
//Returns the index of the first occurence of char c in char* string. If not found -1 is returned.
int get_index(char* string, char c) {
char *e = strchr(string, c);
if (e == NULL) {
return -1;
}
return (int)(e - string);
}
【讨论】:
怎么样:
char *string = "qwerty";
char *e = string;
int idx = 0;
while (*e++ != 'e') idx++;
复制到 e 以保留原始字符串,我想如果您不在乎,您可以对 *string 进行操作
【讨论】: