实现atoi和itoa函数
题目1: 把字符串转化为整数
有整数字符串,"13579", 和 "246810". 请写一个函数把这两个字符串转化为整数
步骤:
- 先判断正负
- 遍历字符串,转换字符为整数
//atoi.cc
#include <stdio.h>
int my_atoi(char *str)
{
bool bmin = false;
int result = 0;
//先判断正负
if ((*str > '9' || *str < '0') && (*str == '+' || *str == '-'))
{
if (*str == '-') bmin = true;
str++;
}
while (*str != '\0')
{
if (*str > '9' || *str < '0') break;
//printf("befter str: %s\n", str);
result = result * 10 + (*str++ - '0');
//printf("after str: %s\n", str);
}
if (*str != '\0') return 0;
return bmin ? -result : result;
}
int main()
{
char a[] = "13579";
char b[] = "246810";
printf("a: %d\n", my_atoi(a));
printf("b: %d\n", my_atoi(b));
}
编译&运行
$ g++ -o atoi atoi.cc
$ ./atoi
a: 13579
b: 246810
基础知识补充
*str++: 它的运算顺序是先返回*str的值,然后str再++。(*str)++: 它的运算顺序是先返回*str的值,然后*str的值再++*(str++): 它的运算顺序是先返回*str的值,然后str再++。和*str++的运算顺序是一样的。++*str: 先将*str的值++,然后再返回*str的值。++(*str): 先将*str的值++,然后再返回*str的值,所以它和++*str是一样的。* (++str),先将str的值++,然后再返回* str的值,和*++str是等价的。*str++ - '0': 表达式的意思是字符 - ’0‘ = 整数,可以通过ASCII码来计算。举个例子:
//ascii.cc
int main()
{
int a = 2;
char c = '3';
char b = '0' + a;
int d = a + (c -'0');
printf("int + char = %c, d: %d\n",b,d);
}
编译运行
$ gcc -g -o ascii ascii.cc
$ ./ascii
int + char = 2, d: 5
可以看到 char b = '0' + a;
'0'的十进制ascii值是4848 + 2 = 50b的值是字符'2', 十进制ascii值是50,对应的值是字符'2',打印出来的值正确; 再看int d = a + (c -'0');c的值是字符'3',对应的十进制ascii是51c- ‘0’ = 51 - 48 = 3int d = a + (c -'0') = a + 3 = 2 + 3 = 5, 打印出来的值正确;
可以得出结论:
- 整数 + ‘0’ =整数值字符, 举例:
2 + '0' = '2'; - 字符 - ‘0‘ = 字符值整数, 举例:
‘2’ - '0' = 2;
题目2:把整数转化为字符串
请把整数123456转化为字符串;
步骤:
- 求出整数的最大位(个/十/百/千/万)
- 遍历位数,将整数转化为字符
// itoa.cc
int my_itoa(long i, char* str)
{
int power = 0, j = 0;
j = i;
//求出整数的最大位
for (power = 1; j>10; j /= 10)
power *= 10;
//遍历位数,将整数转化为字符
for (; power>0; power /= 10)
{
*str++ = '0' + i / power;
i %= power;
}
*str = '\0';
}
int main()
{
char str[7];
my_itoa(123456, str);
printf("str: %s\n", str);
}
编译&运行
$ g++ -g -o itoa itoa.cc -std=c++11
$ ./itoa
str: 123456
--完--
- 原文作者: 留白
- 原文链接: https://zfunnily.github.io/2021/03/atoianditoa/
- 更新时间:2024-04-16 01:01:05
- 本文声明:转载请标记原文作者及链接