I'm wondering how I can convert a string like of letters to their numerical value in an array. For example, A is 0, B is 1. I know I need to use like a for loop like this: for (int i = 0; i < 26; i++), but I'm not sure what code fragment to actually use to do the converting into an int array? Help?
-
You need to post code showing what you have tried.Cory Kendall– Cory Kendall2013-03-18 00:34:50 +00:00Commented Mar 18, 2013 at 0:34
-
Do you mean you want to convert each letter based on its index?Kakalokia– Kakalokia2013-03-18 00:36:10 +00:00Commented Mar 18, 2013 at 0:36
-
@ Ali Alamiri, the intention was to convert the letter to its numerical value. So no, not by index, but rather if given a string like "CAGHS", it would represent the int array: 3 0 6 7 18Sydney Warrenburg– Sydney Warrenburg2013-03-18 01:14:36 +00:00Commented Mar 18, 2013 at 1:14
Add a comment
|
2 Answers
Converting a letter (char) to an integer representing its place in the alphabet is easier than some people realize; all you have to do is:
(int)(c - 'A') // the "distance" between c and 'A' = place of c in alphabet
Loop through the characters of your string and perform this operation for each, storing the results in a new int array.
Comments
You can get the each Char by yourString.charAt(i) and then cast it with (int) this will gave you the Corresponding ASCII then subtract from the ASCII of 'A'. You will have what you want
result = (int)yourString.charAt(i) - (int)'A'
3 Comments
Sydney Warrenburg
so if I have a string like "ESBDGACF" it would print out "4 18 1 3 6 0 2 5" when I printed it?
Sami Eltamawy
It is supposed to do that, but you should consider the spaces while printing each Char and note that this solution is Case sensitive. If you used lower case litter you will have another result @SydneyWarrenburg
Sydney Warrenburg
Thanks much @Abd El-Rahman El-Tamawy. I've already implemented code to convert my string to upper case always. Your help is much appreciated!