Search code examples
csubtractionletters-and-numbers

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.


Solution

  • 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'