C++字符串格式化的几种方式

  1. 使用snprintf格式化字符串
  2. 使用boost::format格式化字符串
  3. 使用stringstream格式化字符串

具体示例

  1. 使用snprintf格式化字符串
#include <stdio.h>
using std::string;
// 准备数据
string haha("haha");
int num = 3;
// 准备格式
string fmt("test string: %s. test number: %d");
char targetString[1024];
// 格式化,并获取最终需要的字符串
int realLen = snprintf( targetString, 
						sizeof(targetString), 
						fmt.c_str(), 
						haha.c_str(), 
						num );

参考链接http://www.cplusplus.com/reference/cstdio/snprintf/

  1. 使用boost::format格式化字符串
#include "boost/format.hpp"
// 准备数据
string haha("haha");
int num = 3;
// 准备格式
boost::format fmt("test string: %s. test number: %d");
// 格式化
fmt % haha % num;
// 获取最终需要的字符串
string targetString = fmt.str();

参考链接https://www.boost.org/doc/libs/1_70_0/libs/format/example/sample_formats.cpp

  1. 使用stringstream格式化字符串
#include <sstream>
using std::stringstream;
// 准备数据
string haha("haha");
int num = 3;
// 准备根据格式造字符串流
stringstream fmt;                       /* 或者使用 ostringstream */
// 造字符串流
fmt << "test string: " << haha << ". test number: " << num;
// 获取最终需要的字符串
string targetString = fmt.str();

参考链接http://www.cplusplus.com/reference/ostream/ostream/operator<</

猜你喜欢

转载自blog.csdn.net/qq_29695701/article/details/99059536
今日推荐