利用Boost库进行字符串与文本处理


背景描述

字符串与文本的处理一直是C++的弱项,虽然C++98提供了一个标准字符串处理里std::string,但是任缺乏很多文本处理的高级特征,如正则表达式和分词,使得不少C++程序员不得不求租与其他语言(如perl,python)。

BOOST库填补了这个空白,boost中有5个主要的字符串与文本处理的程序库。loxical_cast(字符串与数值转换), format(格式化输出), sting_alog(提供了大量的字符串处理函数), tokenizer(分词器), xpressive(正则表达式分析器).

loxical_cas
 

include<boost/loxical_cast.hpp>

using namespace boost;

try{

    int i=loxical_cast<int>("1000");

}

catch(bad_loxical_cast& e){

    cout<<"error: "<<e.what()<<endl;

}

 

format
 

#include<boost/format.hpp>

using namespace boost;

cout<<format("%s:%d+%d=%d")%"sum" %2 %3 %5<<endl;
format fmt("%1%+%2%=%3%");
fmt %2 %5;
fmt %7;
cout<<fmt.str();

 

 

%05d   输出宽度为5的整数,不足位用0补充

%-8.3f 输出左对其宽度为8,小数位为3的浮点数

% 10s  输出10位数的字符串,不足位用空格补齐

 

string_algo
#include<boos/algorithm/string.hpp>

using namespace boost;

 

to_uper();

to_lower();

to_lower_copy();

starts_with();

ends_with();

contians(str1,str2);

is_uper();

tirm_if(str, is_idgit());

find_nth(str,"abc",2);查找第三次出现abc的地方

相关内容