Use of s[i] - '0' [duplicate]

2019-03-06 17:18发布

问题:

This question already has an answer here:

  • How do you convert char numbers to decimal and back or convert ASCII 'A'-'Z'/'a'-'z' to letter offsets 0 for 'A'/'a' …? 4 answers

The following code basically takes a string and converts it into an integer value. What I don't understand is why the int digit = s[i] - '0'; is necessary. Why can't it work by using int digit = s[i] instead? What purpose does the -'0' have?

int main(){

    string s = "123";
    int answer = 0;
    bool is_negative = false;
    if (s[0] == '-')
    {
        is_negative = true;
    }
    int result = 0;
    for (int i = s[0] == '-' ? 1 : 0; i < s.size(); ++i)
    {
        int digit = s[i] - '0';
        result = result * 10 + digit;
    }

    answer = is_negative ? -result : result;
    cout << answer << endl;
    system("pause");
}

回答1:

Firstly, in your question title

the use of '0'

should be written as

the use of s[i] - '0'

That said, by subtracting the ASCII value of char 0 (represented as '0'), we get the int value of the digit represented in char format (ASCII value, mostly.)



回答2:

It's because the value inside s[i] is a char type.

To convert the char '1' into an integer, you do '1' - '0' to get 1. This is determined by position in the ASCII table, char '0' is 48, while char '1' is 49.



回答3:

The reason for the subtraction is that s[i] is, for example, '6'. The value '6' evaluates to 54 (the ascii code). The ASCII code of '0' is 48. So '6' - '0' = 6, which is the char value expressed as an int.



标签: c++ char