8,9年前に書いたはてなダイアリーを閉じたので、参照の多かった記事をサルベージします。
内容も、若干新しくしてます。
使用例
コード
#include <iostream> #include <string> #include <vector> #include <boost/algorithm/string.hpp> int main() { using boost::algorithm::split; std::vector<std::string> buf; split(buf, "a,b,c", boost::is_any_of(",")); for (const auto& str: buf) { std::cout << str << std::endl; } split(buf, "12 33 dc", boost::is_space()); for (const auto& str: buf) { std::cout << str << std::endl; } return 0; }
出力
a b c 12 33 dc
解説
boost::algorithm::split
は第3引数の述部で区切り文字を指定して、第2引数の文字列を分割します。
boost::is_any_of
を使うと、string
の場合、それぞれの文字(char
)を区切り文字として分割を行います。
例えば、boost::is_any_of("#,")
の場合、#
と,
を区切り文字とします。
区切りの間が0文字でも、空文字として追加されます。
std::vector<std::string> buf; split(buf, "a,b,c#d", boost::is_any_of("#,")); for (const auto& str: buf) { std::cout << str << std::endl; }
a b c d
それ以外の述部は、<cctype>
のラッパーになっています。
例えば、boost::is_space()
の場合、std::isspace
のラッパーになっています。