c language: letter and number conversion

 Letters ===》Numbers

#include <stdio.h>
#include <ctype.h>

int main()
{
    char c = '5';
    if (isdigit(c))
    {
        int num = c - '0';
        printf("Number: %d\n", num);
    }
    else
    {
        printf("Not a digit\n");
    }
    return 0;
}

`-'0'` is a commonly used method for converting character numbers to their corresponding integers. The principle of this method is to take advantage of the ASCII code value difference between character numbers and integers.

In the ASCII code table, the code value of character '0' is 48, the code value of character '1' is 49, and so on, the code value of character '9' is 57. Therefore, when we perform the `-'0'` operation on a character number, we actually subtract the ASCII code value of the character '0' from the ASCII code value of the character, thereby obtaining the integer represented by the character.

For example, if we have a character `c = '5'`, then after performing the operation `c - '0'`, we will get the integer 5. This is because the ASCII code value of the character '5' is 53, and the ASCII code value of the character '0' is 48. Subtracting the two gives us 5. 

Numbers ===》Letters (big/small)

nAdd the character constant to the integer 'A'and then subtract 1 to get the corresponding uppercase letter. Similarly, you can use the following code to nconvert an integer to its lowercase equivalent:

#include <stdio.h>

int main()
{
    int n = 1; // A is the first letter of the alphabet
    char c = 'A' + n - 1;
    printf("Uppercase: %c\n", c); // Output: B

    n = 2; // a is the first letter of the alphabet
    c = 'a' + n - 1;
    printf("Lowercase: %c\n", c); // Output: c

    return 0;
}

 

Guess you like

Origin blog.csdn.net/qq_55906687/article/details/131115823