String-related operations-string operations for written test content
The first question about string operations ~~~~~~ Conversion between strings and Integers
Some Considerations for converting strings and integers:
1. The Null String "" and only one positive or negative number should be taken into account. For example, there is nothing behind "+ ".
2. At the same time, the maximum value of a positive integer is 0X7FFF FFFF, and the minimum negative integer is 0x8000 0000. Therefore, you need to determine whether the integer overflow and underflow occur in two cases.
The following code converts a string to an integer:
# Include
# Include
Enum Status {kValid = 0, kInvalid}; int g_nStatus = kValid; // use global variables to record whether the returned integer is valid long StrToIntCore (const char * digit, int minus) {long num = 0; while (* digit! = '\ 0') {// if the end is not read, continue to loop if (* digit> = '0' & * digit <= '9 ') {int flag = minus? -1: 1; num = num * 10 + flag * (* digit-'0 '); // if ((! Minus & num> 0x7FFFFFFF) | (minus & num <(signed int) 0x80000000) {num = 0; break; // exit the loop if removed.} digit ++;} else {num = 0; // If not, the number returned is 0 break; // exit while loop} if (* digit = '\ 0') {g_nStatus = kValid;} return num;} int StrToInt (const char * str) {g_nStatus = kInvalid; int minus = 0; long num = 0; if (str! = NULL & * str! = '\ 0') {if (* str =' + ') {str ++;} else if (* str = '-') {// if it is the symbol str ++; minus = 1 ;}// if it is null after the +-symbol, if (* str! = '\ 0') {num = StrToIntCore (str, minus) ;}} return (int) num ;}int main () {char * p; p = "123567 "; int m = StrToInt (p); printf ("% d", m); system ("pause"); return 0 ;}