数字字符串转换成整型
我们经常会碰到将数字字符串转换成整型的问题,此篇文章给出一种常见的解决方案
知识补充:
‘1’ - ‘0’ = 1
具体事例分析:
char price [6] = {‘1’,‘2’,‘3’,‘4’,‘5’,’\0’};
‘1’ - ‘0’ =1;
1×10 + ‘2’ - ‘0’ = 12;
12 ×10 + ‘3’ - ‘0’ = 123;
123×10 + ‘4’ -‘0’ = 1234;
1234×10 + ‘5’ - ‘0’ = 12345;
代码实现
str2int.c
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
char price[] = "12345";
const char *ptr = price;
int priceNum = 0;
while(*ptr)
{
priceNum *=10;
priceNum += *ptr - '0';
ptr++;
}
printf("priceNum=%d",priceNum);
return 0;
}