c++11之字符串格式化

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

c++11之字符串格式化
1.关于
我知道的,C++20中引⼊了相当⽅便的字符串格式化,有兴趣的朋友,可以看下库,截⾄⽬前,它实现了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";
输出结果:。

相关文档
最新文档