1.關於
我知道的,C++20中引入了相當方便的字符串格式化,有興趣的朋友,可以看下fmt庫,截至目前,它實現了c++20中引入的字符串格式化絕大部分功能。
2.format
既然c++11中沒有方便的函數可以實現字符串格式化,那我們就自己寫個c++版本的字符串格式化函數,上代碼
std::string版本
template<typename ... Args>
static std::string str_format(const std::string &format, Args ... args)
{
auto size_buf = std::snprintf(nullptr, 0, format.c_str(), args ...) + 1;
std::unique_ptr<char[]> buf(new(std::nothrow) char[size_buf]);
if (!buf)
return std::string("");
std::snprintf(buf.get(), size_buf, format.c_str(), args ...);
return std::string(buf.get(), buf.get() + size_buf - 1);
}
std::wstring版本
template<typename ... Args>
static std::wstring wstr_format(const std::wstring &format, Args ... args)
{
auto size_buf = std::snprintf(nullptr, 0, format.c_str(), args ...) + 1;
std::unique_ptr<char[]> buf(new(std::nothrow) char[size_buf]);
if (!buf)
return std::wstring("");
std::snprintf(buf.get(), size_buf, format.c_str(), args ...);
return std::wstring(buf.get(), buf.get() + size_buf - 1);
}
Note: 包含頭文件 #include <memory>
3.一個例子
下面演示調用上面的2個函數
std::string str = str_format("%d.%d.%d", 1, 0, 1);
std::string wstr = str_format("%d.%d.%d", 2, 3, 2);
cout << "str = " << str.c_str() << "\n";
cout << "wstr = " << wstr.c_str() << "\n";
輸出結果: