前言 我们得知道什么是atoi函数! atoi函数是一个将字符串转化为整数的函数 
atoi的规则是:跳过不可见字符,碰到负号或者数字开始转换,转换到非数字字符为止。 根据规则我们分为三类: 一:是第一个非空字符是“+”或者“-”,判断其后是否紧跟有数字字符,将后面紧跟的连续的(不间断数字字符的才会纳入解析)数字字符解析成整数 二:第一个非空字符就是数字字符,从该数字字符开始,将后面紧跟的连续的数字字符解析成整数。 三:非上述两种情况,返回0。 ps:不间断数字字符的第一个字符为‘0’也不会打印的 
 ——————————————————————————————————————— 我们来模拟一下atoi函数吧! 先看一下 如果他的参数符合下列条件就返回真 代码:
int my_atoi(const char* str)
{
int ret = 0;
int i = 0;
int j = 0;
if (isspace(str[i]))
{
i++;
}
if (str[i] == '+' || str[i] == '-' || (str[i] > '0' && str[i] < '9'))
{
j = i;
if (str[i] == '+' || str[i] == '-')
{
j++;
while (str[j] >= '0' && str[j] <= '9')
{
ret = ret * 10 + str[j] - '0';
j++;
}
}
while (str[j] >= '0' && str[j] <= '9')
{
ret = ret * 10 + str[j] - '0';
j++;
}
if (str[i] == '-')
return -ret;
else
return ret;
}
return 0;
}
int main()
{
char arr1[] = "-123 123";
printf("第一种情况:%d\n", my_atoi(arr1));
char arr2[] = "123 123";
printf("第二种情况:%d\n", my_atoi(arr2));
char arr3[] = "A123 123";
printf("第三种情况:%d\n", my_atoi(arr3));
return 0;
}
 本文结束!
|