Converting Letters to Numbers in C

前端 未结 10 1213
悲&欢浪女
悲&欢浪女 2020-11-30 07:22

I\'m trying to write a code that would convert letters into numbers. For example A ==> 0 B ==> 1 C ==> 2 and so on. Im thinking of writing 26 if statements. I\'m wondering

10条回答
  •  庸人自扰
    2020-11-30 07:47

    I wrote this bit of code for a project, and I was wondering how naive this approach was.

    The benefit here is that is seems to be adherent to the standard, and my guess is that the runtime is approx. O(k) where k is the size of the alphabet.

    int ctoi(char c)
    {
        int index;
        char* alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    
        c = toupper(c);
    
        // avoid doing strlen here to juice some efficiency.
        for(index = 0; index != 26; index++)
        {
            if(c == alphabet[index])
            {
                return index;
            }
        }
    
        return -1;
    }
    

提交回复
热议问题