E.g.
In C I\'d just subtract the char from \'A\', but I don\'t seem
The output you are expecting is just the offset
of a upper case letter with respect to 'A'
. So just subtract the Unicode value of 'A'
from the unicode value of the letter whose offset is needed.
example: 'B' - 'A' = 1
actually the weak point of the other solutions here is that they involve string creation
public enum Alphabet {
A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z
}
you can now use the ordinal function to get the offset in here. e.g. Alphabet.L.ordinal();
However, since I assume you are dealing with functions, here is a more useful definition
public enum Alphabet {
A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z;
public static int getNum(String targ) {
return valueOf(targ).ordinal();
}
public static int getNum(char targ) {
return valueOf(String.valueOf(targ)).ordinal();
}
}
Notes: unlike other languages, you can declare an enum in it's own file exactly like a class. Actually enums as shown above can contain fields and methods too, the fields are statically created, and are very hard to break. In fact the use of an enum with only local methods and variables and a single enum type called INSTANCE is the recommended way to create a singleton as it is unbreakable even by reflection.
You may want to think about slipping a toUppercase() call in there too if you are not controlling the calls to the function
If you are looking to more dynamically create your alphabet rather than use a predefined alphabet, you should be looking into maps
You can do simple math with chars in Java as well:
System.out.println('A' - 'A');
will output 0.
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
return alphabet.indexOf( myChar );
Here's different implementation which runs in logarithmic time:
Class
import java.util.Arrays;
import java.util.Collections;
public class CharacterIndex {
private char[] characters = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
public int index(char character) {
assert characters != null;
return Arrays.binarySearch(characters, Character.toUpperCase(character));
}
}
Unit Test
import org.junit.Before;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
public class CharacterIndexTest {
private CharacterIndex characterIndex;
@Before
public void createIndex() {
characterIndex = new CharacterIndex();
}
@Test
public void testIndexOfLetterA() {
assertEquals(0, characterIndex.index('A'));
assertEquals(0, characterIndex.index('a'));
}
@Test
public void testNotALetter() {
assertEquals(-1, characterIndex.index('1'));
}
}
You could use java.lang.Character.toUpperCase('a') - 65;