How to get numeric position of alphabets in java ?
Suppose through command prompt i have entered abc then as a output i need to get 123 how can i get the numeric position of alphabets in java?
Thanks in advance.
To get the position, subtract 96 from ASCII value of input character. In case if you convert input letter in to upper case, you need to subtract 64 as ASCII value for upper case alphabet stars from 65.
So, each letter has a unique numeric value via the Character class.
String str = "abcdef"; char[] ch = str.toCharArray(); for(char c : ch){ int temp = (int)c; int temp_integer = 96; //for lower case if(temp<=122 & temp>=97) System.out.print(temp-temp_integer); }
Output:
123456
@Shiki for Capital/UpperCase letters use the following code:
String str = "DEFGHI"; char[] ch = str.toCharArray(); for(char c : ch){ int temp = (int)c; int temp_integer = 64; //for upper case if(temp<=90 & temp>=65) System.out.print(temp-temp_integer); }
Output:
456789
Another way to do this problem besides using ASCII conversions is the following:
String input = "abc".toLowerCase(); final static String alphabet = "abcdefghijklmnopqrstuvwxyz"; for(int i=0; i < input.length(); i++){ System.out.print(alphabet.indexOf(input.charAt(i))+1); }
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