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";
输出结果:
原文链接: https://www.cnblogs.com/pandamohist/p/13711779.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/203064
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!