【入力】

 "a,b,c"


【出力】

 <a> <b> <c>


【サンプル】

#include <cstdlib>
#include <iostream>
#include "boost/tokenizer.hpp"

using namespace std;

int main(int argc, char *argv[])
{
//型宣言
typedef boost::tokenizer<boost::char_separator<char> > csv_tokenizer;
//区切りクラスの生成
boost::char_separator<char> sep(",");
//解析対象
std::string str = "a,b,c";
//解析クラス
csv_tokenizer tokens(str, sep);


//区切った文字を取り出す
for(csv_tokenizer::iterator tok_iter = tokens.begin(); tok_iter != tokens.end(); ++tok_iter)
std::cout << "<" << *tok_iter << "> ";


std::cout << "\n";

system("PAUSE");
return EXIT_SUCCESS;
}



【説明】

boost::tokenizer を使用すると、区切り文字で区切った文字列を取得するのが簡単です。

Iteratorを使用して次々に文字列を取り出せます。Iteratorが分からない人は、こちら を参照。

tokenizerはコンパイルの必要がないのでそのまま使用できます。

区切り文字を複数指定することもできます。


漏補

漏:

tokenizerを使用している間に解析対象のstring(上記の場合str)を変更すると、正しい結果が得られません。


補:

tokenizer使用中は解析対象を変更しない方針にする。

どうしても変更したい場合は、tokenizerに渡す値はコピー文字列にし、元の文字列を変更する。

string copyed = str;

tokenizer tokens(copyed, sep);



参考:

boostとは?