空白で区切られた単語で構成される文字列の単語を反復処理するにはどうすればよいですか?
なお、私は C 文字列関数やその種の文字操作/アクセスには興味がありません。効率よりもエレガントさを重視します。現在の私の解決策は次のとおりです。
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
string s = "Somewhere down the road";
istringstream iss(s);
do {
string subs;
iss >> subs;
cout << "Substring: " << subs << endl;
} while (iss);
}
ベストアンサー1
私はこれを使用して、文字列を区切り文字で分割します。最初の関数は結果を事前に構築されたベクトルに格納し、2 番目の関数は新しいベクトルを返します。
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
template <typename Out>
void split(const std::string &s, char delim, Out result) {
std::istringstream iss(s);
std::string item;
while (std::getline(iss, item, delim)) {
*result++ = item;
}
}
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
split(s, delim, std::back_inserter(elems));
return elems;
}
このソリューションでは空のトークンがスキップされないことに注意してください。そのため、次の例では 4 つの項目が見つかりますが、そのうちの 1 つは空です。
std::vector<std::string> x = split("one:two::three", ':');