How to map character to numeric position in java?

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.


Use the indexOf method on a String object. For example,

"ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf('F')

returns 5.

Tags:

Java