很遗憾的是,C++ 标准库 std::string并没有提供类似于sprintf之类的字符串格式化函数,所以就自己来实现咯。
#include
#include
#include
template
static std::string formatString(const std::string &format, Args ... args)
{
auto size = std::snprintf(nullptr, 0, format.c_str(), args ...) + 1; // Extra space for '\0'
std::unique_ptr buf(new char[size]);
std::snprintf(buf.get(), size, format.c_str(), args ...);
return std::move(std::string(buf.get(), buf.get() + size - 1)); // We don't want the '\0' inside
}
template
static std::wstring formatString(const std::wstring &format, Args ... args)
{
auto size = std::swprintf(nullptr, 0, format.c_str(), args ...) + 1; // Extra space for '\0'
std::unique_ptr buf(new wchar_t[size]);
std::swprintf(buf.get(), size, format.c_str(), args ...);
return std::move(std::wstring(buf.get(), buf.get() + size - 1)); // We don't want the '\0' inside
}
template
static void formatStringEx(std::string &dst, const std::string &format, Args ... args)
{
auto size = std::snprintf(nullptr, 0, format.c_str(), args ...) + 1; // Extra space for '\0'
std::unique_ptr buf(new char[size]);
std::snprintf(buf.get(), size, format.c_str(), args ...);
dst = { buf.get(), buf.get() + size - 1 };
}
template
static void formatStringEx(std::wstring &dst, const std::wstring &format, Args ... args)
{
auto size = std::swprintf(nullptr, 0, format.c_str(), args ...) + 1; // Extra space for '\0'
std::unique_ptr buf(new wchar_t[size]);
std::swprintf(buf.get(), size, format.c_str(), args ...);
dst = { buf.get(), buf.get() + size - 1 };
}
示例程序:
int main(int argc, char *argv[])
{
std::string str;
std::wstring wstr;
std::string str_1 = formatString("%s, %d, %f, %.2lf", "today", 2, 2.1, 0.1);
formatStringEx(str, "%s, %d, %f, %.2lf", "today", 2, 2.1, 0.1);
std::wstring wstr_1 = formatString(L"%s, %d, %f, %.2lf", L"today", 2, 2.1, 0.1);
formatStringEx(wstr, L"%s, %d, %f, %.2lf", L"today", 2, 2.1, 0.1);
return 0;
}