[英]subtracting letters in c
I would like to know how to "subtract letters" in C: 我想知道如何在C语言中“减去字母”:
I mean, I have 2 letters, 'a' and 'c' and i want to execute 'c'-'a'='b' which is 3-1=2. 我的意思是,我有2个字母,“ a”和“ c”,我想执行3-1 = 2的“ c”-“ a” =“ b”。
How is it possible to obtain the same behaviour in C? 如何在C中获得相同的行为?
I can conversion Letters->Numbers but how to manage the limited lenght of the alphabet? 我可以将字母转换为数字,但是如何管理字母的有限长度 ? Thank you. 谢谢。
you can treat the letters as numbers and then add the letter 'a'
back to normalize it 您可以将字母视为数字,然后再添加字母'a'
以将其标准化
so 所以
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
If you want the number difference just use diff
from my answer ( ans
will give you the letter). 如果您想要数字diff
在我的答案中使用diff
( ans
会给您字母)。
This will not wrap around so 这样不会环绕
'a' - 'b'
will result in -1
(or the character before a) 将结果为-1
(或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;
This will give: 这将给出:
'z'
for 'b'-'c'
'z'
代表'b'-'c'
'y'
for 'b'-'d'
'y'
代表'b'-'d'
Are you looking this? 你在看这个吗?
char a1,a2,a3;
a3 = a1 - a2 + 'a';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.