C++で文字列をトークン化する
この投稿では、C++で文字列をトークン化する方法について説明します。
1.文字列ストリームの使用
C++で文字列をトークン化する一般的な解決策は、 std::istringstream
、これは文字列を操作するためのストリームクラスです。次のコードは、抽出演算子を使用してストリームからトークンを抽出し、それらをコンテナーに挿入します。
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 <iostream> #include <vector> #include <string> #include <sstream> #include <iterator> using namespace std; int main() { string str = "Tokenize a string in C++"; vector<string> tokens; istringstream iss(str); string s; while (iss >> s) { tokens.push_back(s); } for (const string &s: tokens) { cout << s << endl; } return 0; } |
出力:
Tokenize
a
string
in
C++
これは、を使用して入力文字列からトークンを抽出する別のアプローチです。 std::istream_iterator
。 The std::istream_iterator
で無効にされていない限り、デフォルトで空白をスキップします std::noskipws
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#include <iostream> #include <vector> #include <string> #include <sstream> #include <iterator> using namespace std; int main() { string str = "Tokenize a string in C++"; istringstream iss(str); vector<string> tokens; copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter(tokens)); for (const string &s: tokens) { cout << s << endl; } return 0; } |
出力:
Tokenize
a
string
in
C++
イニシャライザリストを使用すると、コードをさらに次のように短縮できます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <iostream> #include <vector> #include <string> #include <sstream> #include <iterator> using namespace std; int main() { string str = "Tokenize a string in C++"; istringstream iss(str); vector<string> tokens = {istream_iterator<string>{iss}, istream_iterator<string>{}}; for (const string &s: tokens) { cout << s << endl; } return 0; } |
出力:
Tokenize
a
string
in
C++
2.正規表現を使用する
文字列をトークン化するもう1つのもっともらしい解決策は、正規表現を使用することです。これは、シーケンスに対してパターンマッチングを実行するための標準です。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#include <iostream> #include <vector> #include <string> #include <regex> using namespace std; int main() { string str = "Tokenize a string in C++"; regex reg("\\s+"); sregex_token_iterator iter(str.begin(), str.end(), reg, -1); sregex_token_iterator end; vector<string> tokens(iter, end); for (const string &s: tokens) { cout << s << endl; } return 0; } |
出力:
Tokenize
a
string
in
C++
3.Boostライブラリの使用
Boost C++ライブラリは、このタスクのためのいくつかのユーティリティクラスも提供します。 The Boost tokenizer classは、特定の文字を区切り文字として解釈することにより、シーケンスに含まれるトークンのビューを提供します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <string> #include <boost/tokenizer.hpp> using namespace std; using namespace boost; int main() { string str = "Tokenize a string in C++"; char_separator<char> sep(" "); tokenizer<char_separator<char>> tokens(str, sep); for (const string &s: tokens) { cout << s << endl; } return 0; } |
出力:
Tokenize
a
string
in
C++
これで、C++で文字列をトークン化することができます。