よくある文字列の分割処理は、boost::splitを使うと簡単です。
boost::splitの引数
boost::splitは3つの引数をとります。
- 出力シーケンス
- 入力コレクション
- 区切り文字を判断する述語
boost::splitで文字列をカンマで分割する
#include <iostream>
#include <string>
#include <boost/algorithm/string.hpp>
#include <boost/foreach.hpp>
std::string s = "abc,def,ghi,jkl"; //分割する文字列
std::list<std::string> results; //分割結果を格納する変数
boost::split(results, s, boost::is_any_of(",")); //,区切り
//分割結果を出力
BOOST_FOREACH(std::string p, results) {
std::cout << p << std::endl;
}
複数の区切り文字で分割する例
#include <iostream>
#include <string>
#include <boost/algorithm/string.hpp>
#include <boost/foreach.hpp>
std::string s = "2011/02/09 20:19:33";
std::list<std::string> results;
//スラッシュ、スペース、コロンで分割
boost::split(results, s, boost::is_any_of("/ :"));
BOOST_FOREACH(std::string p, results) {
std::cout << p << std::endl;
}
空白文字で分割
#include <iostream>
#include <string>
#include <boost/algorithm/string.hpp>
#include <boost/foreach.hpp>
std::string s = "More Effective C++";
std::list<std::string> results;
//空白文字で分割
boost::split(results, s, boost::is_space());
BOOST_FOREACH(std::string p, results) {
std::cout << p << std::endl;
}