整數類型轉換成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);
}
這幾種方法中方法一速度很快。