您的位置:首页 > 其它

StrToInt实现

2016-04-04 21:28 225 查看

StrToInt实现

字符串转整型数的整体思想很简单,但是实现起来,细节问题很容易忽略,故写此博客来加深记忆。

- 细节处理

参数中const变量指针使用;

空指针处理;

字符串前面空格处理;

字符串正负号处理;

字符前面 0 字符的处理;

最大整数和最大负数溢出处理;

错误字符输入处理

- 函数实现

int StrToInt(const char *str)
{
int result = 0;
int flag = 1;
// 判断字符串是否是NULL
if (str == NULL)
{
return -1;
}
// 跳过前面的空格
while ((*str) == ' ')
str++;
// 判断字符串正负号
if ((*str) == '-')
{
flag = -1;
str++;
}
if ((*str) == '+')
{
flag = 1;
str++;
}
// 跳过字符串前面的0
while ((*str) == '0')
{
str++;
}
// 遍历剩下字符串,进行字符转数字
while((*str) != '\0')
{
// 判断字符是否合法
if ((*str >= '0') && (*str <= '9'))
{
int temp = result;
// 正数处理
if (flag == 1)
{
result = (result * 10) + (*str - '0');
}
// 负数处理
else if (flag == -1)
{
result = (result * 10) - (*str - '0');
}
// 溢出判断
if (((flag == 1) && (result < temp)) || ((flag == -1) && (result > temp)))
return -1;
str++;
}
else
{
return -1;
}
}
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  字符串转整数