E.g.
In C I'd just subtract the char from 'A', but I don't seem to be able to do this in java.
Declare a Hashmap in Java of {char, int}. Traverse in the string, check if the Hashmap already contains the traversed character or not. If it is present, then increase its count using get() and put() function in Hashmap. Once the traversal is completed, traverse in the Hashmap and print the character and its frequency.
In Java, char and int are compatible types so just add them with + operator. c + x results in an integer, so you need an explicit casting to assign it to your character varaible back.
So to find this there is a very easy way. Let us look at it. To get it we can find the ASCII value of the alphabet and then we can subtract 64 from it for the uppercase Alphabet and for lowercase we need to subtract 96 from it. Or First, you can convert the string to upper or lower case and then can find it.
Use the indexOf
method on a String object. For example,
"ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf('F')
returns 5.
You can do simple math with chars in Java as well:
System.out.println('A' - 'A');
will output 0.
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
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