如何在C中找到字符串中字符的索引? [英] How do I find the index of a character within a string in C?

查看:111
本文介绍了如何在C中找到字符串中字符的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个字符串qwerty,我希望找到 e 字符的索引位置它。 (在这种情况下,索引将是 2

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)

如何在C中执行此操作?

How do I do it in C?

我找到了 strchr 函数,但它返回一个指向字符而不是索引的指针。

I found the strchr function but it returns a pointer to a character and not the index.

推荐答案

只需从strchr返回的内容中减去字符串地址:

Just subtract the string address from what strchr returns:

char *string = "qwerty";
char *e;
int index;

e = strchr(string, 'e');
index = (int)(e - string);

这篇关于如何在C中找到字符串中字符的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆