Home >Backend Development >C++ >How Can I Efficiently Convert Single Digits from a String to Integers in C/C ?
In programming, you often encounter situations where a string of digits needs to be converted into individual integers. While accessing each character by index is straightforward, converting those characters to integers can seem challenging.
The popular atoi() function requires a string argument, leading to the idea of converting each character to a string and then using atoi(). However, there is a more direct and efficient approach.
The key is to recognize that the character encodings for digits are sequential. In ASCII, UTF-x, and most other encoding systems, '0' has an encoding of 48, while '9' has an encoding of 57.
Leveraging this, you can extract the integer value of a digit by subtracting the character from '0' or 48. For instance:
char c = '1'; int i = c - '0'; // i is now equal to 1, not '1'
This is equivalent to:
char c = '1'; int i = c - 48; // i is now equal to 1, not '1'
While both expressions produce the same result, the first option (c - '0') is generally considered more readable.
The above is the detailed content of How Can I Efficiently Convert Single Digits from a String to Integers in C/C ?. For more information, please follow other related articles on the PHP Chinese website!