This seems like a very simple question, but nothing surprising has been written about it on the Internet, and it’s hard for me to do it correctly on my own. What is the best way to implement a modular comparison function for ASCII characters in Java, so that comparison wraps the end of the alphabet? I want to use it for an “between” function, which can split the entire alphabet into arbitrary locations and correctly return “true” when asked if “y” is between “x” and “b”.
I already found all the questions and answers that talk about modular arithmetic for characters, so I know how to do modular addition (moving characters) with this code:
char shifted = (((original - 'a') + 1) % 26) + 'a';
However, this is based on Java, built in modular arithmetic functions that have no equivalent for comparison. Even if I use simple ints, I cannot ask Java if a <b <c mod 26 (which should return true if a = 24, b = 25 and c = 1).
So, the general question: what is the best way to implement modular comparison operations in Java? If this is too complex a problem, is there at least one way to make such comparisons work for the ASCII alphabet?
source
share