C++でのstringの分割方法は何ですか?
C++には組み込みのstring split関数はありませんが、自作のsplit関数を実装して文字列を分割することができます。以下は簡単なサンプルコードです。
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
std::vector<std::string> split(const std::string& str, char delimiter) {
std::vector<std::string> tokens;
std::stringstream ss(str);
std::string token;
while (std::getline(ss, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
int main() {
std::string str = "Hello,World,How,Are,You";
std::vector<std::string> tokens = split(str, ',');
for (const std::string& token : tokens) {
std::cout << token << std::endl;
}
return 0;
}
上記のコード例では、split関数は文字列と区切り文字をパラメーターとして受け取り、文字列を区切り文字で分割し、分割結果を格納する文字列ベクトルを返します。
最初に、入力文字列strをstd::stringstreamを使用してストリームオブジェクトssに変換します。その後、ssからstd::getline関数を使ってトークンを1行ずつ読み込み、それをtokensベクターに追加します。
最後、メイン関数で文字列”Hello,World,How,Are,You”をsplit関数に渡し、区切り文字を’,’とします。その後、ループを使用してtokensベクター内の分割結果を走査し、各分割結果を印刷します。
上記のコードを実行した結果は:
Hello
World
How
Are
You