减去c中的字母 [英] subtracting letters in c
问题描述
我想知道如何在C语言中减去字母":
我的意思是,我有2个字母,"a"和"c",我想执行3-1 = 2的"c"-'a'='b'.
如何在C中获得相同的行为?
我可以转换 Letters-> Numbers ,但是如何管理字母的有限长度? 谢谢.
I would like to know how to "subtract letters" in C:
I mean, I have 2 letters, 'a' and 'c' and i want to execute 'c'-'a'='b' which is 3-1=2.
How is it possible to obtain the same behaviour in C?
I can conversion Letters->Numbers but how to manage the limited lenght of the alphabet? Thank you.
推荐答案
您可以将字母视为数字,然后再添加字母'a'
以对其进行规范化
you can treat the letters as numbers and then add the letter 'a'
back to normalize it
如此
char c1 = 'a';
char c2 = 'c';
int diff = c2 - c1; //'c' - 'a' = 2
char ans = diff + 'a' - 1; //add 'a' and subtract 1 to normalize it
如果您想要数字差异,只需在我的答案中使用diff
(ans
会给您字母).
If you want the number difference just use diff
from my answer (ans
will give you the letter).
这不会绕过来
'a' - 'b'
将导致-1
(或a之前的字符)
will result in -1
(or the character before a)
如果要使用底片处理底片,则必须进行检查
If you want to handle negatives with a wrap you have to check it
int diff = c2 - c1;
char ans;
diff > 0 ? ans = diff + 'a' - 1 : 'z' + diff + 1;
这将给出:
-
'z'
表示'b'-'c'
-
'y'
表示'b'-'d'
'z'
for'b'-'c'
'y'
for'b'-'d'
这篇关于减去c中的字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!