如何在C语言中的字母中获取字符的位置? [英] How to get character's position in alphabet in C language?

查看:249
本文介绍了如何在C语言中的字母中获取字符的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种快速的方法来检索C中英文字母中给定字符的位置?

Is there a quick way to retrieve given character's position in the english alphabet in C?

类似:

int position = get_position('g');

推荐答案

int position = 'g' - 'a' + 1;

在C中,char值可转换为int值,并采用其ASCII值.在这种情况下,'a'与97相同,而'g'为103.由于字母表在ASCII字符集中是连续的,因此从值中减去'a'即可得到其相对位置.如果您认为'a'是第一个(而不是第零个)位置,请加1.

In C, char values are convertible to int values and take on their ASCII values. In this case, 'a' is the same as 97 and 'g' is 103. Since the alphabet is contiguous within the ASCII character set, subtracting 'a' from your value gives its relative position. Add 1 if you consider 'a' to be the first (instead of zeroth) position.

这篇关于如何在C语言中的字母中获取字符的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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