Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 224
user2099816 Avatar asked Feb 22 '13 15:02

user2099816


People also ask

How do I convert letters to numbers?

The Letter-to-Number Cipher (or Number-to-Letter Cipher or numbered alphabet) consists in replacing each letter by its position in the alphabet , for example A=1, B=2, Z=26, hence its over name A1Z26 .

How do I convert a string to a number?

You convert a string to a number by calling the Parse or TryParse method found on numeric types ( int , long , double , and so on), or by using methods in the System. Convert class. It's slightly more efficient and straightforward to call a TryParse method (for example, int.

Do letters have numerical value in java?

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


2 Answers

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.

like image 74
Sergey Kalinichenko Avatar answered Sep 17 '22 13:09

Sergey Kalinichenko


String s = "hello world";
String t = "";
for (int i = 0; i < s.length(); ++i) {
    char ch = s.charAt(i);
    if (!t.isEmpty()) {
        t += " ";
    }
    int n = (int)ch - (int)'a' + 1;
    t += String.valueOf(n);
}
System.out.println(t);

This does not deal with space etc.

like image 39
Joop Eggen Avatar answered Sep 16 '22 13:09

Joop Eggen