简体   繁体   中英

subtracting letters in c

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.

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:

  1. 'z' for 'b'-'c'
  2. 'y' for 'b'-'d'

Are you looking this?

char a1,a2,a3;
a3 = a1 - a2 + 'a';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM