整数类型转换成string的几种方法

整数类型转换成string的几种方法

转载请说明出处:http://blog.csdn.net/cywosp/article/details/8980633

最近遇到了要将整数类型转化成string的问题,网上搜罗了一下,总结了几种方法。如下:

方法一:

template<typename T>
static size_t Convert (char buf[], const T value)
{
	static const char digits[] = "9876543210123456789";
	static const char* zero = digits + 9;

	T i = value;
	char* p = buf;

	do
	{
		int lsd = static_cast<int>(i % 10);
		i /= 10;
		*p++ = zero[lsd];
	} while (i != 0);

	if (value < 0)
	{
		*p++ = '-';
	}
	*p = '\0';
	std::reverse (buf, p); // #include <algorithm>

	return p - buf;
}

static inline void IntToString (std::string& out, const int value)
{
    char buf[32];
    Convert<int>  (buf, value);
    out.append (buf);
}

方法二:

static inline void IntToString (std::string& out, const int value)
{
    char buf[32];
    snprintf (buf, sizeof (buf), "%d", value);  // snprintf is thread safe #include <stdio.h>
    out.append (buf);
}

方法三:

static inline void IntToString (std::string& out, const int value)
{
    std::strstream ss; // #include <strstream>
    ss <<  value;
    ss >> out;
}

方法四:

static inline void IntToString (std::string& out, const int value)
{
    char buf[32];
    itoa (value, buf, 10); // #include <stdlib.h>
    out.append (buf);
}

这几种方法中方法一速度很快。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值