使用boost库拆分字符串

来源:互联网 发布:途风旅游 怎么样 知乎 编辑:程序博客网 时间:2024/06/05 05:41

在日常开发中经常会遇到分割字符串的要求,boost库为我们提供了一个方便的分词器——boost::tokenizer。现在就让我们学习一下boost库的分词器。

 
#include <string>   
  1. #include <iostream>   
  2.   
  3. #include <boost/format.hpp>   
  4. #include <boost/tokenizer.hpp>  
  5. #include <boost/algorithm/string.hpp>  
  6.   
  7. int _tmain(int argc, _TCHAR* argv[])  
  8. {  
  9.     // 待分割的字符串   
  10.     std::string strTag = _T("I Come from China");  
  11.     // 定义分割方式为英文逗号,中文逗号和空格,构造一个分词器,   
  12.     boost::char_separator<char> sep(" ,,");  
  13.     typedef boost::tokenizer<boost::char_separator<char> >  
  14.         CustonTokenizer;  
  15.     CustonTokenizer tok(strTag,sep);  
  16.   
  17.     // 输出分割结果   
  18.     std::vector<std::string> vecSegTag;  
  19.     for(CustonTokenizer::iterator beg=tok.begin(); beg!=tok.end();++beg)  
  20.     {  
  21.         vecSegTag.push_back(*beg);  
  22.     }  
  23.   
  24.     for (size_t i  =0;i<vecSegTag.size();i++)  
  25.     {  
  26.         std::cout<<vecSegTag[i]<<std::endl;  
  27.     }  
  28.   
  29.     // 尝试下分割中文字符   
  30.     vecSegTag.clear();  
  31.     std::string strTag2 = _T("我叫小明,你呢,今天天气不错");  
  32.     CustonTokenizer tok2(strTag2,sep);  
  33.     for(CustonTokenizer::iterator beg=tok2.begin(); beg!=tok2.end();++beg)  
  34.     {  
  35.         vecSegTag.push_back(*beg);  
  36.     }  
  37.   
  38.     for (size_t i  =0;i<vecSegTag.size();i++)  
  39.     {  
  40.         std::cout<<vecSegTag[i]<<std::endl;  
  41.     }  
  42.   
  43.     getchar();  
  44.     return 0;  
  45. }  


 

        

         但是boost::tokenizer的一个缺点是它不支持分割unicode字符串。所以要分割unicode字符串我们需要使用boost库提供的另一个接口——boost::split。它的使用比boost::tokenizer还要方便,请看下面代码:

[cpp] view plaincopyprint?
  1. #include <string>   
  2. #include <iostream>   
  3.   
  4. #include <boost/format.hpp>   
  5. #include <boost/tokenizer.hpp>  
  6. #include <boost/algorithm/string.hpp>  
  7.   
  8. int _tmain(int argc, _TCHAR* argv[])  
  9. {  
  10.     std::wcout.imbue(std::locale("chs"));  
  11.     // 待分割的字符串   
  12.     std::wstring strTag = _T("I Come from China");  
  13.   
  14.     std::vector<std::wstring> vecSegTag;  
  15.      // boost::is_any_of这里相当于分割规则了  
  16.     boost::split(vecSegTag, strTag,boost::is_any_of(_T(" ,,")));  
  17.   
  18.     for (size_t i  =0;i<vecSegTag.size();i++)  
  19.     {  
  20.         std::wcout<<vecSegTag[i]<<std::endl;  
  21.     }  
  22.   
  23.     vecSegTag.clear();  
  24.     std::wstring strTag2 = _T("我叫小明,你呢,今天天气不错");  
  25.     boost::split(vecSegTag, strTag2, boost::is_any_of(_T(" ,,")));  
  26.   
  27.     for (size_t i  =0;i<vecSegTag.size();i++)  
  28.     {  
  29.         std::wcout<<vecSegTag[i]<<std::endl;  
  30.     }  
  31.     getchar();  
  32.     return 0;  
  33. }  

 

原创粉丝点击