2

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?

3
  • You need to post code showing what you have tried. Commented Mar 18, 2013 at 0:34
  • Do you mean you want to convert each letter based on its index? Commented 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 18 Commented Mar 18, 2013 at 1:14

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

so if I have a string like "ESBDGACF" it would print out "4 18 1 3 6 0 2 5" when I printed it?
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
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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.