stringのsplit

boost::algorithm.splitを使う

参考:Boost.String Algorithm - Faith and Brave - C++で遊ぼう

#include <iostream>
#include <vector>
#include <string>
#include <boost/algorithm/string.hpp>

using namespace std;
using namespace boost::algorithm;

int main()
{
  string s = "a,b.c,as/df";
  vector<string> results;
  split(results, s, boost::is_any_of(",./"));

  cout << "要素数: " << results.size() << endl;
  for (int i = 0; i < results.size(); i++){
    cout << results[i] << endl;
  }
}

boost::is_any_ofに渡した文字のどれかで区切れる

要素数: 5
a
b
c
as
df


と思ったがboost::regex_splitの方が便利かも

参考:http://ml.tietew.jp/cppll/cppll/article/7189

区切り文字の前後にスペースが入っていても無視する例

#include <iostream>
#include <boost/regex.hpp>
#include <string>

using namespace std;
using namespace boost;

int main(int argc, char* argv[]){
  string str = "a, b, c/d.e f ,g";
  cout << str << endl;
  
  regex delimiter(" *[,/.] *");

  vector<string> results;
  regex_split(back_inserter(results), str, delimiter);

  for(int i = 0; i < results.size(); i++){
    cout << '"' << results[i] << '"' << endl;
  }

  return 0;
}
g++ -O regex_split.cpp  -o regex_split -I/opt/local/include/boost /opt/local/lib/libboost_regex-mt.a
a, b, c/d.e f ,g
"a"
"b"
"c"
"d"
"e f"
"g"


ちなみに区切り文字を()でくくると、区切り文字列の方が抜き出せる。
個人的にはマッチした部分と分割した部分が交互に出てくる方がありがたい・・・と思ったが、これはどっちかというと「文字列から正規表現に該当する部分を全て抜き出す」ってことか。

  regex delimiter("( *[,/.] *)");
a, b, c/d.e f ,g
", "
", "
"/"
"."
" ,"