Is there a way to find the distance of letters in Java?
What I mean is for example:
A -> C = 3 (as A, B, C)
B -> G = 6 (as B, C, D, E, F, G)
R -> Z = 9 (as R, S, T, U, V, W, X, Y, Z)
(I am looking for distance that is inclusive of the first letter)
Thanks!
You can do this:
int diff = Character.toLowerCase('C') - Character.toLowerCase('A');
This works, because each char
is associated with an ASCII value. 'C' has the value 67 and 'A' is 65, thus 'C' - 'A'
== 67 - 65
. Note that this only works as long as all of the characters are uppercase or all characters are lowercase.
For strings containing a single character:
String s1 = "A";
String s2 = "c";
int result = ((int)s2.toLowerCase().charAt(0) - (int)s1.toLowerCase().charAt(0)) + 1;
If you are working with just characters (no strings), then Java's Character
class has a static toLowerCase()
method.
Edit
For the case where the result may be negative ('A' - 'C'):
result = Math.abs(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With