Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get numeric position of alphabets in java? [duplicate]

Tags:

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.

like image 251
New to android development Avatar asked Jan 16 '12 12:01

New to android development


People also ask

How do you find the numeric position of the alphabet?

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.

Do letters have numerical value in Java?

So, each letter has a unique numeric value via the Character class.


2 Answers

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

like image 146
RanRag Avatar answered Sep 28 '22 23:09

RanRag


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); } 
like image 22
Alekxos Avatar answered Sep 29 '22 00:09

Alekxos