Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Letter Distance?

Tags:

java

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!

like image 685
01jayss Avatar asked Nov 29 '22 02:11

01jayss


2 Answers

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.

like image 193
jrad Avatar answered Dec 04 '22 17:12

jrad


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);
like image 21
Chris Dargis Avatar answered Dec 04 '22 16:12

Chris Dargis