[Boost基础]字符串和文本处理——lexical_cast词汇转换
字符串和文本处理
字符串与文本处理一直是C++的弱项,虽然C++98标准提供了一个标准字符串类std::string,暂缓燃眉之急,但C++仍然缺乏很多文本处理的高级特性,如正则表达式,分词等等,使得不少C++程序员不得不转向其他语言(eg:python)。
Boost填充了C++这方面的空白。 Lexical_cast、format(类似”printf”格式的操作)和C标准库函数功能类似,它们关注字符串的表示,可以将数值转化为字符串,对输出做精确的格式化。String_algo(字符串算法)库提供了大量常用的字符串处理函数,可以满足90%以上的应用需求,剩下的10%可以使用tokenizer(是一个分词器)和xpressive(是一个灵活且功能强大的正则表达式分析器,同时也是一个语法分析器)。
lexical_cast官网教程
#pragma once#include <boost/lexical_cast.hpp>#include <string>#include <iostream>#include <conio.h>using namespace std; //数字与字符串之间的转换void test1(){ using namespace boost;int x=lexical_cast<int>("100"); //string->intlong y=lexical_cast<long>("20000"); //string->longfloat pai=lexical_cast<float>("3.14159e5"); //string->floatdouble e=lexical_cast<double>("2.71828"); //string->doublecout<<x<<" "<<y<<" "<<pai<<" "<<e<<endl;//100 2000 314159 2.71828//从输出结果中分析:在使用lexical_cast时要注意,要转换成数字的字符串中只能有数字和小数点,不能出现有字母(eg:e/E,123L,0x100),而且lexical_cast不支持高级的格式控制,不能把数字转换成指定格式的字符串,如果需要更高级的格式控制,可使用std::stringstream或者boost::format。如有异常可使用:bad_lexical_casttry{cout<<lexical_cast<int>("0x100")<<endl;}catch (bad_lexical_cast& e){cout<<"error:"<<e.what()<<endl;//error:bad lexicl cast:source type value could not be interpreted as target} string str1=lexical_cast<string>(852); //int->stringstring str2=lexical_cast<string>(0.618); //float->stringstring str3=lexical_cast<string>(0x10); //16进制int->stringcout<<str1<<" "<<str2<<" "<<str3<<endl;//852 0.61799999999999 17} void test(char t){cout<<"press key====="<<t<<endl;switch (t){ case '1':test1();break;// case '2':test2();break;// case '3':test3();break;// case '4':test4();break;case 27:case 'q':exit(0);break;default: cout<<"default "<<t<<endl;break;}}int main(){while(1){test(getch());} return 0;}
虽然lexcical_cast的用法非常像转型操作符,但他仅仅是在用法上模仿了转型操作符而已,它实际上是一个模板函数。lexcical_cast内部使用了标准库的流操作,因此转换对象有如下要求:
转换起点对象是可流输出的:即定义了opreator<<转换终点对象是可流输入的:即定义了opreator>>转换终点对象必须是可缺省构造和可拷贝构造的C++的内置类型(int,double等)和std::string都是lexcical_cast最常用的工作搭档。但对于STL中的容器和其他自定义类型,这些条件一般都不满足,不能使用lexical_cast。