整数类型转换成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); }
这几种方法中方法一速度很快。