C语言 如何在C中的字符串中找到字符的索引?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3217629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I find the index of a character within a string in C?
提问by bodacydo
Suppose I have a string "qwerty"and I wish to find the index position of the echaracter in it. (In this case the index would be 2)
假设我有一个字符串"qwerty",我希望在其中找到e字符的索引位置。(在这种情况下,索引将是2)
How do I do it in C?
我如何在 C 中做到这一点?
I found the strchrfunction but it returns a pointer to a character and not the index.
我找到了该strchr函数,但它返回一个指向字符而不是索引的指针。
回答by wj32
Just subtract the string address from what strchr returns:
只需从 strchr 返回的内容中减去字符串地址:
char *string = "qwerty";
char *e;
int index;
e = strchr(string, 'e');
index = (int)(e - string);
Note that the result is zero based, so in above example it will be 2.
请注意,结果是基于零的,因此在上面的示例中它将是 2。
回答by R.. GitHub STOP HELPING ICE
You can also use strcspn(string, "e")but this may be much slower since it's able to handle searching for multiple possible characters. Using strchrand subtracting the pointer is the best way.
您也可以使用,strcspn(string, "e")但这可能会慢得多,因为它能够处理搜索多个可能的字符。使用strchr和减去指针是最好的方法。
回答by abelenky
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.
}
This code is currently untested, but it demonstrates the proper concept.
此代码目前未经测试,但它展示了正确的概念。
回答by Dan Molik
What about:
关于什么:
char *string = "qwerty";
char *e = string;
int idx = 0;
while (*e++ != 'e') idx++;
copying to e to preserve the original string, I suppose if you don't care you could just operate over *string
复制到 e 以保留原始字符串,我想如果您不在乎,您可以对 *string 进行操作
回答by Varun Narayanan
This should do it:
这应该这样做:
//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);
}

