如何在 C 语言中找到字符串中字符的索引?
假设我有一个字符串 "qwerty"
并且我希望找到其中 e
字符的索引位置。 (在这种情况下,索引将为2
)
我如何在 C 中做到这一点?
我找到了 strchr 函数,但它返回一个指向字符的指针,而不是索引。
Suppose I have a string "qwerty"
and I wish to find the index position of the e
character in it. (In this case the index would be 2
)
How do I do it in C?
I found the strchr
function but it returns a pointer to a character and not the index.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您还可以使用
strcspn(string, "e")
但这可能会慢得多,因为它能够处理搜索多个可能的字符。使用strchr并减去指针是最好的方法。You can also use
strcspn(string, "e")
but this may be much slower since it's able to handle searching for multiple possible characters. Usingstrchr
and subtracting the pointer is the best way.该代码目前未经测试,但它演示了正确的概念。
This code is currently untested, but it demonstrates the proper concept.
这应该可以做到:
This should do it:
怎么样:
复制到 e 以保留原始字符串,我想如果你不关心你可以只对 *string 进行操作
What about:
copying to e to preserve the original string, I suppose if you don't care you could just operate over *string
只需从 strchr 返回的内容中减去字符串地址:
请注意,结果是从零开始的,因此在上面的示例中它将是 2。
Just subtract the string address from what strchr returns:
Note that the result is zero based, so in above example it will be 2.