0

Say I have a char extracted from a string ( str.at(i) ), how would I convert that char to a number such that A=0, B=1, C=2... Z=25? Thanx in advance

Blake Doeren
  • 665
  • 4
  • 10
  • 16

2 Answers2

2

Assuming that the string is already in the A-Z range, you could do char_value - 'A'.

This assumes that the letters are all consecutive. So 'B' == 'A' + 1, 'C' == 'A' + 2, etc. In ASCII, this assumption is correct.

luiscubal
  • 24,773
  • 9
  • 57
  • 83
  • Yes this worked! thank you! If you could, can you explain why this works? – Blake Doeren Oct 06 '13 at 21:44
  • 1
    @BlakeDoeren Added some details. Hopefully, this should clarify things. – luiscubal Oct 06 '13 at 21:47
  • Thank you very much! This is probably the quickest response I've gotten on stack overflow yet. – Blake Doeren Oct 06 '13 at 21:47
  • @BlakeDoeren: with all those responses to your questions, be them quick or slow, would you mind to [accept](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) one every now and then? – Jongware Oct 06 '13 at 23:19
0

Each Character has a specific ASCII code !! Like A = 65 , b = 66 .. etc !! If you simply subtract 65 or 'A' from each character , you will get the desired int

eg :

int a = charArray[i] - 65; 

if: charArray[i] = A
then: a = 0 

& so on!!

logc
  • 3,813
  • 1
  • 18
  • 29