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

查看:13
本文介绍了如何在 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天全站免登陆