简体   繁体   中英

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

Assuming that the string is already in the AZ 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM