Search code examples
c++stringintegerasciiletters

C++ Converting/casting String letters to integer values (ASCII)


I'm currently doing a project where I need to create two data structures that will be used to contain strings. One of them has to be a form of linked list, and I've been adivsed to seperate the words out into seperate lists inside of it for each letter of the alphabet. I'm required to think about efficiency so I have an array of Head pointers of size 26, and am wanting to convert the first character of the word given into an integer so I can put it into the subscript, such as:

//a string called s is passed as a parameter to the function
int i = /*some magic happens here*/ s.substr(0, 1);
currentPointer = heads[i]; //then I start iterating through the list

I've been searching around and all I've seemd to have found is how to covert number characters that are in strings into integers, and not letter characters, and am wondering how on earth I can get this working without resorting to a huge and ugly set of if statements


Solution

  • When you are setting i to the value of the first character, you are getting the ASCII value. So i is out of your 0-25 range : See man ascii You can reduce it by substraction of the first alaphabet ascii letter. (Be care full with the case)

     std::string   s("zoro");
     int   i = s[0];
    
     std::cout << "Ascii value : " << i << " Reduced : " << i - 'a' << std::endl;
    

    Which produce the ASCII value 'z' = 112 and 25 for the reduced value, as expected.