Skip to content
Advertisement

Java – how to convert letters in a string to a number?

I’m quite new to Java so I am wondering how do you convert a letter in a string to a number e.g. hello world would output as 8 5 12 12 15 23 15 18 12 4.
so a=1, b=2, z=26 etc.

Advertisement

Answer

Since this is most likely a learning assignment, I’ll give you a hint: all UNICODE code points for the letters of the Latin alphabet are ordered alphabetically. If the code of a is some number N, then the code of b is N+1, the code of c is N+2, and so on; the code of Z is N+26.

You can subtract character code points in the same way that you subtract integers. Since the code points are alphabetized, the following calculation

char ch = 'h';
int pos = ch - 'a' + 1;

produces the sequence number of h, i.e. 8. If you perform this calculation in a loop, you would get the result that you need.

Note that the above formula works only with characters of the same register. If your input string is in mixed case, you need to convert each character to lower case before doing the calculation, otherwise it would come out wrong.

Advertisement