C++: 文字列をスペースで分割
文字列を区切ってベクタに代入するエレガントな方法。
・コード
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | #include <string> #include <vector> #include <iostream> #include <sstream> #include <iterator> //------------------------------------------------------------------------------ // Split a string with space //------------------------------------------------------------------------------ std::vector<std::string> split(std::string const & s) { std::istringstream iss(s); return std::vector<std::string>( std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>()); } int main() { std::vector<std::string> a = split( "a dramatic turn of events" ); std::vector<std::string> b = split( "1 23 456 7890" ); for ( int i = 0; i < ( int )a.size(); ++i) { std::cout << a[i] << std::endl; } for ( int i = 0; i < ( int )b.size(); ++i) { std::cout << b[i] << std::endl; } return 0; } |
・出力
1 2 3 4 5 6 7 8 9 | a dramatic turn of events 1 23 456 7890 |
参考:
http://blog.goo.ne.jp/linux_ekyu/e/3a89ea531b6a0ea6997dd68238b198ce
0 件のコメント:
コメントを投稿