c++11之字符串格式化

546次阅读

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";

输出结果:
c++11之字符串格式化

yiywain
版权声明:本文于2022-08-09转载自c++11之字符串格式化,共计1081字。
转载提示:此文章非本站原创文章,若需转载请联系原作者获得转载授权。