- 追加された行はこの色です。
- 削除された行はこの色です。
[[Programming]]
* boost ライブラリを使って,トークン化とベクトル化 [#oe860c72]
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <boost/tokenizer.hpp>
using namespace std;
int main(int arg, char *argv[]){
vector<string> v;
string finame, foname;
string ss;// strtok を使う場合は,
// 読み込んだ行はchar 変数におさめる
//char ss[256];
ifstream fin;
typedef boost::tokenizer<> tokenizer1;
finame = argv[1];
fin.open(finame.c_str());
if(!fin) return 1;
while(fin >> ss){
tokenizer1 tok1( ss);
for( tokenizer1::iterator it=tok1.begin(); it!=tok1.end(); ++it )
// cout << "TOKEN: " << *it << endl;
v.push_back(*it);
}
fin.close();
cout << v.size() << endl;
}
以下は[[ここ:http://www.kmonos.net/alang/boost/classes/tokenizer.html]]からの引用
>
必要なヘッダ
<boost/tokenizer.hpp>
出来ること
文字列切り分け
リファレンス
en / jp
sample
#include <iostream>
#include <string>
#include <boost/tokenizer.hpp>
using namespace std;
int main()
{
string str1 = "this is a pen";
// デフォルトでは、区切り文字(空白とかコンマとか)で分割する。
typedef boost::tokenizer<> tokenizer1;
tokenizer1 tok1( str1 );
for( tokenizer1::iterator it=tok1.begin(); it!=tok1.end(); ++it )
cout << "TOKEN: " << *it << endl;
string str2 = "20020903";
// 4文字、2文字、2文字に分割してみる。
const int offsets[] = {4,2,2};
boost::offset_separator ofs( offsets, offsets+3 );
typedef boost::tokenizer<boost::offset_separator> tokenizer2;
tokenizer2 tok2( str2, ofs );
for( tokenizer2::iterator it=tok2.begin(); it!=tok2.end(); ++it )
cout << "TOKEN: " << *it << endl;
return 0;
}
<
実行例
TOKEN: this
TOKEN: is
TOKEN: a
TOKEN: pen
TOKEN: 2002
TOKEN: 09
TOKEN: 03
etc
まぁ、見たまんまです。コマンドラインの解析とか、 コンマ区切りテキストデータの解釈などに役立ちそう。 wchar_t型文字列の切り分けなども可能なので、 日本語環境でも使えるのではないかと。分割関数をちゃんと用意すれば、 マルチバイト文字列でもOKだと思われます。。