C++ format格式化输出字符串简单版实现

本实例基于C++11的可变长参数实现:

#include <iostream>
#include <sstream>
#include <string>

static void _format_help(
    std::ostringstream& os, const std::string& format, std::size_t offset)
{
	os << format.substr(offset, format.size() - offset);
}

template <class T, class... Args>
static void _format_help(
	std::ostringstream& os, const std::string& format, std::size_t offset, T arg, Args...args)
{
	std::size_t off = format.find("{}", offset);
	if (off == std::string::npos) {
		os << format.substr(offset, format.size() - offset);
		return;
	}
	os << format.substr(offset, off - offset) << arg;
	_format_help(os, format, off + 2, args...);
}

/* 
	格式化输出成字符串,需要格式化的地方使用{}即可
	如:
		format("this is {}, age: {}, height: {}m", "Alice", 18, 1.72);
	输出:"this is Alice, age: 18, height: 1.72m"
		format("this is {}, age: {}, height: {}m {}m", "Alice", 18, 1.72);
	输出:"this is Alice, age: 18, height: 1.72m {}m"
		format("this is {}, age: {}, height: {}m {}m", "Alice", 18, 1.72, 555, 666);
	输出:"this is Alice, age: 18, height: 1.72m 555m"
*/
template <class... Args>
std::string format(const std::string& format, Args... args)
{
	std::ostringstream os;
	_format_help(os, format, 0, args...);
	return std::move(os.str());
}

int main(int argc, char* argv[])
{
	std::cout << format("one {} two {} three {} {} {} {}", 1, 2, 3, 4.5, "123", "this is my test") << std::endl;
	std::cout << format("this is {}, age: {}, height: {}m", "Alice", 18, 1.72) << std::endl;
	std::cout << format("this is {}, age: {}, height: {}m {}m", "Alice", 18, 1.72) << std::endl;
	std::cout << format("this is {}, age: {}, height: {}m {}m", "Alice", 18, 1.72, 555, 666) << std::endl;
	return 0;
}

/*
one 1 two 2 three 3 4.5 123 this is my test
this is Alice, age: 18, height: 1.72m
this is Alice, age: 18, height: 1.72m {}m
this is Alice, age: 18, height: 1.72m 555m
*/

若编译器支持C++20,则可以直接使用<format>工具库的format函数,效果类似。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值