问题
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.
回答1:
you can treat the letters as numbers and then add the letter 'a'
back to normalize it
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).
This will not wrap around so
'a' - 'b'
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;
This will give:
'z'
for'b'-'c'
'y'
for'b'-'d'
回答2:
Are you looking this?
char a1,a2,a3;
a3 = a1 - a2 + 'a';
来源:https://stackoverflow.com/questions/10778920/subtracting-letters-in-c