数字字符串转换成这个字符串对应的数字(十进制、十六进制)
(1)数字字符串转换成这个字符串对应的数字(十进制)
要求:这个字符串参数必须包含一个或者多个数字,函数应该把这些数字转换为整数并且返回这个整数。如果字符串参数包含任何非数字字符,函数就返回零。不必担心算数溢出。
提示:你每发现一个数字,把当前值乘以10,并把这个值和新的数字所代表的值相加。
思路:字符指针减去’0’(对应ASCII值为48),即将其对应的ASCII码值转换为整型。第一次循环*str指向的是字符’1’,其对应的ASCII码值为49,而’0’对应ASCII码值为48,所以运用”*str-‘0’“目的是将字符’1’转换成数字1,后面以此类推。
代码如下:
#include <stdio.h> #include <assert.h>
int my_atoi(char *str) { int n = 0; int flag = 0; assert(str); if(*str == '-') { flag = 1; str++; } while(*str >= '0' && *str <= '9') { n = n*10 + (*str - '0'); str++; } if(flag == 1) { n = -n; } return n; } int main () { char a[] = "12"; char b[] = "-123"; printf("%d\n%d\n",my_atoi(a),my_atoi(b)); return 0; }
(2)数字字符串转换成这个字符串对应的数字(十六进制)
要求:这个字符串参数必须包含一个或者多个数字,函数应该把这些数字转换为整数并且返回这个整数。如果字符串参数包含任何非数字字符,函数就返回零。不必担心算数溢出。
提示:你每发现一个数字,把当前值乘以16,并把这个值和新的数字所代表的值相加。
思路:字符指针减去’0’(对应ASCII值为48),即将其对应的ASCII码值转换为整型。第一次循环*str指向的是字符’1’,其对应的ASCII码值为49,而’0’对应ASCII码值为48,所以运用”*str-‘0’“目的是将字符’1’转换成数字1,后面以此类推。
代码如下:
#include <stdio.h> #include <assert.h> #include <iostream>
using namespace std; int change(char* str) { assert(str); int result = 0; int flag = 0; if (*str == '-') { flag = 1; str++; } while (*str) { if (*str >= '0' && *str <= '9') result = result * 16 + (*str - '0'); else if (*str >= 'a' && *str <= 'f') result = result * 16 + (*str - 'a' + 10); else if (*str >= 'A' && *str <= 'F') result = result * 16 + (*str - 'A' + 10); else { cout << "非法字符!" << endl; return 0; } str++; } if (flag == 1) result = -result; return result; } int main() { char str[] = "-16"; int res = change(str); cout << res << endl; return 0; }