Trying to convert uppercase char to lowercase in C without using a function

后端 未结 4 697
耶瑟儿~
耶瑟儿~ 2021-01-27 02:58

I am trying to convert a char element from an char *argv[] array to lowercase from uppercase without using a function. I want to add 32 to the ascii integer.

When I try

4条回答
  •  野性不改
    2021-01-27 03:32

    This is from my own C++ library, but it works for C too as well.

    Self-Optimized (Library Function)

    // return the specified letter in lowercase
    char tolower(int c)
    {
        // (int)a = 97, (int)A = 65
        // (a)97 - (A)65 = 32
        // therefore 32 + 65 = a
        return c > 64 && c < 91 ? c + 32 : c;
    }
    // return the specfied letter in uppercase
    char toupper(int c)
    {
        // (int)a = 97, (int)A = 65
        // (a)97 - (A)65 = 32
        // therefore 97 - 32 = A
        return c > 96 && c < 123 ? c - 32 : c;
    }
    

    The return value is a printable char. However, some modern compilers may have optimized the code as this already if you're going to do the way below.

    Readable

    char tolower(int c)
    {
        return c >= 'A' && c <= 'Z' ? c + ('a' - 'A') : c;
    }
    char toupper(int c)
    {
        return c >= 'a' && c <= 'z' ? c - ('a' - 'A') : c;
    }
    

    Note that the difference between a and A is a 32 constant.

提交回复
热议问题