Blake Doeren
Blake Doeren

Reputation: 705

Letters to Numbers with C++ chars

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

Upvotes: 0

Views: 5320

Answers (2)

Bilal Wasim
Bilal Wasim

Reputation: 17

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!!

Upvotes: 0

luiscubal
luiscubal

Reputation: 25141

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.

Upvotes: 2

Related Questions