2. 几个简单的例子
// simple_example_1.cpp #include<iostream> #include<boost/tokenizer.hpp> #include<string> int main(){ using namespace std; using namespace boost; string s = "This is, a test"; tokenizer<> tok(s); for(tokenizer<>::iterator beg=tok.begin(); beg!=tok.end();++beg){ cout << *beg << "\n"; } }
// simple_example_3.cpp #include<iostream> #include<boost/tokenizer.hpp> #include<string> int main(){ using namespace std; using namespace boost; string s = "12252001"; int offsets[] = {2,2,4}; // 这里指定了三个步长 offset_separator f(offsets, offsets+3); tokenizer<offset_separator> tok(s,f); for(tokenizer<offset_separator>::iterator beg=tok.begin(); beg!=tok.end();++beg){ cout << *beg << "\n"; } }
template<typename Iter>
× char_separator 主要是用于解析基于特定字符分割的需求offset_separator(Iter begin,Iter end,bool bwrapoffsets = true, bool breturnpartiallast = true)
explicit char_separator(const Char* dropped_delims,const Char* kept_delims = "",
/** * @auth lemo.lu * @date 2011.11.03 * * example of Boost tokenizer template usage,This example uses delimiter * separator. */ // stl header #include <iostream> // iostream #include <string> // string #include <fstream> // ifstream // boost #include <boost/tokenizer.hpp> // boost Tokenizer int main(){ std::ifstream passwdFile; passwdFile.open("/etc/passwd",std::ifstream::in); // store password line char passwdString[256]; typedef boost::tokenizer<boost::char_separator<char> > passwdTokenizer; // set a TokenizerFunction , dropped delimiters ":" and keep delimiters "" boost::char_separator<char> tokenSep(":", "", boost::keep_empty_tokens); // passwd format information static const char* passwd_st[] = { "Account","password","UID","GID","GECOS","Dir","Shell" }; // iterator the passwd file while(passwdFile.good()) { // get line passwdFile.getline(passwdString,256); passwdTokenizer tok(std::string(passwdString), tokenSep); int passwd_c = 0; for(passwdTokenizer::iterator curTok=tok.begin(); curTok!=tok.end(); ++curTok) std::cout << passwd_st[passwd_c++] << ":" << *curTok << std::endl; std::cout << "---------------------" << std::endl; }passwdFile.close();}
部分结果如下:
Account:root
password:x
UID:0
GID:0
GECOS:root
Dir:/root
Shell:/bin/bash
---------------------
Account:daemon
password:x
UID:1
GID:1
GECOS:daemon
Dir:/usr/sbin
Shell:/bin/sh
---------------------