C++ Boost库:简介和第一个示例程序
C++ Boost库:数值转换 lexical_cast
C++ Boost库:字符串格式化 format
C++ Boost库:字符串string_algo
C++ Boost库:字符串算法string_algo
C++ Boost库:类型推导BOOST_AUTO/BOOST_TYPEOF
C++ Boost库:分词处理库 tokenizer
C++ Boost库:windows下编译Boost库
C++ Boost库:日期时间库 date_time
C++ Boost库:智能指针scoped_ptr
C++ Boost库:数组智能指针 scoped_array
C++ Boost库:共享所有权的智能指针 shared_ptr
C++ Boost库:工厂函数 make_shared
C++ Boost库:共享有权的数组智能指针shared_array
C++ Boost库:弱引用智能指针 weak_ptr
C++ Boost库:禁止拷贝 nocopyable
C++ Boost库:计时器 timer
C++ Boost库:普通数组array
C++ Boost库:散列容器 unordered_set、unordered_multiset
C++ Boost库:散列容器 unordered_map、unordered_multimap
C++ Boost库:双向映射容器 bimap
C++ Boost库:环形缓冲区 circular_buffer
C++ Boost库:动态多维数组 multi_array
C++ Boost库:使用property_tree解析XML和JSON
C++ Boost库:简化循环 BOOST_FOREACH
C++ Boost库:随机数库 Random
C++ Boost库:引用库 ref
C++ Boost库:绑定库 bind
C++ Boost库:线程库 thread 跨平台多线程
C++ Boost库:互斥量 mutex
Highscore - Boost C++ 库 - 字符串处理
1. C/C++格式化
在字符串处理中少不了格式化字符串;C++
中传统的格式化函数是C语言的 printf
、sprintf
,但它一个很大的问题就是不安全。因此,在STL
中引入了 stringstream
来实现安全格式化,但是 stringstream
却远不如 sprintf
来得直观。
printf("%s %d %c", "hello", 111, 'C')
2. boost格式化
boost::format
提供了一个和C
的 printf
类似的格式化字串语法定义,同时也保有了C++
的 ostraem
的各项优势,对于要做格式化输出的C++
程序开发人员来说,boost::format
是个相当好用的函数库。使用format
需包含头文件boost/format.hpp
。
typedef basic_format<char> format;
示例代码:
#include <iostream>
using namespace std;
#include<boost/format.hpp>
int main()
{
using boost::format;//使用format
//使用一
format fmt("%1% , %2% !!!"); //先定义对象
fmt % 123;
fmt % "hello";
cout << fmt << endl;
//使用二, 可以不按顺序,可以重复指定
format fmt2(" %2% ----- %1% ----- %2% !!!"); //先定义对象
fmt2 % 123;
fmt2 % "hello";
cout << fmt2 << endl;
//使用三, 可以重复使用
format fmt3(" %2% ----- %1% ----- %2% !!!");
fmt3 % 123;
fmt3 % "hello";
cout << fmt3 << endl;
fmt3 % 1.23456;
fmt3 % 'C' ;
cout << fmt3 << endl;
//用法四,链式使用
cout << format("****%1%****%2%!!!") % "hello"%1.2345f << endl;
cout << (format("****%1%****%2%!!!") % "hello")%1.2345f << endl;
//用法五,可以使用printf中的格式符
cout << format(" %d , %c ,%f , %s") % 666 % 'A'%1.2345f%"Boost" << endl;
//N$指定用哪个参数
cout << format("---%2$s -----%1$s---") %"Boost" % "Hello"<< endl;
//用法六,直接转为string
int age = 20;
const char *name = "zhangsan";
//替代sprintf
format fmt6("name: %1% age %2%");
fmt6%name%age;
string strStu = fmt6.str();//直接转为字符串
cout << strStu << endl;
return 0;
}