C++ Boost

Introduction

boostのTokenizerは、文字列や他の文字記号の列をトークンの組に簡単に分解でき、しかも融通が利く。 以下に文章を単語毎に分解する簡単な例を示す。

// 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";
   }
}

文字列を分解する方法は TokenizerFunction によって指定可能である。 もしなにも指定しなければ、デフォルトの TokenizerFunction としてchar_delimiters_separator<char>が使用される。 char_delimiters_separator<char>は、空白や句読点で文字列を区切る。 ここでは、escaped_list_separator と呼ばれる別の TokenizerFunction を使用した例を挙げる。 この TokenizerFunction はコンマで区切られた値 (csv) の上位集合の行を構文解析する。 そのフォーマットは以下のような感じである。

Field 1,"putting quotes around fields, allows commas",Field 3

以下に処理前の文字列を3つの部分に分解する例を示す。

// simple_example_2.cpp
#include<iostream>
#include<boost/tokenizer.hpp>
#include<string>

int main(){
   using namespace std;
   using namespace boost;
   string s = "Field 1,\"putting quotes around fields, allows commas\",Field 3";
   tokenizer<escaped_list_separator<char> > tok(s);
   for(tokenizer<escaped_list_separator<char> >::iterator beg=tok.begin(); beg!=tok.end();++beg){
       cout << *beg << "\n";
   }
}

また、何か面白いことをするには TokenizerFunctions をコンストラクタに渡さなければならない。 一つの例として offset_separator がある。このクラスは文字列をオフセットに基づいたトークンに分解する。

文字列 12252001 をオフセット2,2,4で構文解析すると 12 25 2001 となる。 以下にその構文解析の例を示す。

// 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";
   }
}

 


© Copyright John R. Bandela 2001. Permission to copy, use, modify, sell and distribute this document is granted provided this copyright notice appears in all copies. This document is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose.

Japanese Translation Copyright © 2003 Akihiro Yamasaki
オリジナルの、及びこの著作権表示が全ての複製の中に現れる限り、この文書の複製、利用、変更、販売そして配布を認める。このドキュメントは「あるがまま」に提供されており、いかなる明示的、暗黙的保証も行わない。また、いかなる目的に対しても、その利用が適していることを関知しない。