这篇文章将为大家详细讲解有关如何高效实现整型数字转字符串int2str,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
将数字转换成字符串有很多方法,现在给出一种高效的实现方法。
char* int2str(unsigned int values)
{
const char digits[11] = "0123456789";
char* crtn = new char[32];
crtn += 31;
*crtn = '\0';
do
{
*--crtn = digits[values%10];
} while (values /= 10);
return crtn;
}
以上是没有考虑那么一点点空间的问题;如果考虑那点空间问题,可以这样做。
char* int2str(unsigned int values)
{
int len = 0;
const char digits[11] = "0123456789";
unsigned int tvalue = values;
while(tvalue >= 100)
{
tvalue /= 100;
len += 2;
}
if (tvalue > 10)
len += 2;
else if(tvalue > 0)
len++;
char* crtn = new char[len+1];
crtn += len;
*crtn = '\0';
do
{
*--crtn = digits[values%10];
} while (values /= 10);
return crtn;
}
同样,带符号的整数一样的做法。
关于“如何高效实现整型数字转字符串int2str”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。