itoa和atoi是两个常常考察的两个函数,下面是关于两个函数我的一个实现方法。
一、itoa的实现方法思路:
1、使用了static作为存储方式,考虑到32位和64位机器的int数据长度的不同,字符串数组设置也应该不同,同时负数应该给予标志位‘-’符号。
2、负数%余数仍是负数,在+‘0’时会出现错误。
3、字符串由于%从低位计算,所以需要翻转字符串。
以下是具体的实现代码:
#include<stdio.h>
#include<string.h>
char* my_itoa(int num)
{
//0、定义储存的数组结构大小,初始化数组
#ifdef __INT64__
static char ch[1 + 19 + 1]; //考虑到unsigned类型位20位 unsigned传值时需要 1 + 20 + 1
#else
static char ch[1 + 10 + 1]; //-2x xxxx xxxx + '\0' 最大12位
#endif
memset(ch, '\0', sizeof(ch));
//1、设置标志位,设置字符串开始位置
int ilow = 0, ihigh = 0;
if (num < 0)
{
num = -num;
ch[0] = '-';
ilow = ihigh = 1;
}
//2.0、将num转换成文本,由于用%,自低位向高位保存,所以字符串是反向的
do
{
ch[ihigh++] = num % 10 + '0';
}while((num /= 10) > 0);
//2.1、翻转字符串
char *plow = ch + ilow;
char *phigh = ch + ihigh - 1; //ihigh 指向了'\0'
char chTemp;
while (plow < phigh)
{
chTemp = *plow;
*plow = *phigh;
*phigh = chTemp;
plow++;
phigh--;
}
return ch;
}
二、atoi的实现方法思路
1、输入的字符串应该检查地址是否为NULL,如果是,则报错,输出为0。
2、输入的字符串应该跳过空格和制表符。
3、输入的字符串应该有判断是否溢出,如有,输出溢出前的字符串,并且给出提示。
4、输入的字符串到非字符时停止。
具体代码如下:
int my_atoi(const char* str)
{
if (NULL == str)
{
printf("错误:输入的字符串地址为NULL\n");
return 0;
}
//0、过滤文本中的' '和'\t'制表符
while ((*str == ' ') || (*str == '\t'))
str++;
//1、设置标志位
int iflag = 1;
if (*str == '+')
{
str++;
}
else if (*str == '-')
{
str++;
iflag = -1;
}
else
{
NULL;
}
/* 2、字符串转换成数字,这里为了判断是否越界,需要设置两个int来判断大小,
在未越界的情况下,前int的绝对值必定小于后int的绝对值。如果相反,则表
示越界,应该用前一个int,并给出越界提示! */
int iExitNum = 0; //代表有无字符串
int iPreNum = 0, iNextNum = 0;
while ((*str <= '9') && (*str >= '0'))
{
iExitNum = 1;
iNextNum = iPreNum * 10 + (*str++ - '0');
if (iNextNum < iPreNum)
{
printf("提示:字符串所表示的数字已经超出计算机所储存的int类型最大范围!\n");
return iPreNum * iflag;
}
else
{
iPreNum = iNextNum;
}
}
if (iExitNum == 0)
{
printf ("错误:该字符串前序数字!\n");
}
return iPreNum * iflag;
}
接下来我们写两个测试打印程序如下
void printf_itoa(int num)
{
printf("输入数字为:%24d,输出字符串为:%24s\n", num, my_itoa(num));
}
void printf_atoi(const char* str)
{
printf("输入字符串为:%24s,输出字符串为:%24d\n", str, my_atoi(str));
}
具体的测试如下:
int main()
{
//测试程序 itoa
printf("测试函数,my_itoa()\n");
printf_itoa(123);
printf_itoa(1234567890);
printf_itoa(-123);
printf_itoa(-12345678);
printf_itoa(0);
printf_itoa(-0);
printf_itoa(-1234567890);
//测试程序 atoi
printf("测试函数, my_atoi()\n");
printf_atoi("1234sdasdf");
printf_atoi("+1234sdasdf");
printf_atoi(" 1234sdasdf");
printf_atoi(" +1234sdasdf");
printf_atoi(" 1234sdasdf");
printf_atoi(" +1234sdasdf");
printf_atoi("-1234sdasdf");
printf_atoi(" -1234sdasdf");
printf_atoi(" -12345678901sdasdf");
printf_atoi(" -123456789sdasdf");
printf_atoi(" -0sdasdf");
printf_atoi(" +0sdasdf");
printf_atoi("0sdasdf");
printf_atoi("we-1234sdasdf");
printf_atoi("eqw-1234sdasdf");
printf_atoi(NULL);
printf_atoi(" -23");
printf_atoi(" -1234sdasdf");
return 0;
}