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.
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 .
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.
So, each letter has a unique numeric value via the Character class.
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.
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.
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