文字列の単語を繰り返し処理しようとしています。
この文字列は、空白で区切られた単語で構成されていると考えられます。
なお、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);
}
もっとエレガントな方法はありませんか?
STLにはそのような方法はすでに用意されていません。
しかし,C言語のstrtok()
関数を,std::string::c_str()
メンバを使って使うか,自分で書くことができます.以下は、Googleで検索して見つけたコードサンプルです("STL string split ")。
void Tokenize(const string& str,
vector<string>& tokens,
const string& delimiters = " ")
{
// Skip delimiters at beginning.
string::size_type lastPos = str.find_first_not_of(delimiters, 0);
// Find first "non-delimiter".
string::size_type pos = str.find_first_of(delimiters, lastPos);
while (string::npos != pos || string::npos != lastPos)
{
// Found a token, add it to the vector.
tokens.push_back(str.substr(lastPos, pos - lastPos));
// Skip delimiters. Note the "not_of"
lastPos = str.find_first_not_of(delimiters, pos);
// Find next "non-delimiter"
pos = str.find_first_of(delimiters, lastPos);
}
}
引用元: http://oopweb.com/CPP/Documents/CPPHOWTO/Volume/C++Programming-HOWTO-7.html
コードサンプルについて質問がある場合は、コメントを残していただければ説明します。
また、イテレータという typedef
を実装していないから、あるいは <<
演算子をオーバーロードしていないからといって、それが悪いコードだということにはなりません。私はC言語の関数を頻繁に使っています。例えば、printf`とscanf`はどちらもstd::cin`やstd::cout`よりも(かなり)速く、fopen`の構文はバイナリ型にはずっと優しいですし、より小さなEXEを生成する傾向もあります。
この 「パフォーマンスよりもエレガンスを」 という話に乗ってはいけません。
あなたのように std::stringstream
を使用することは全く問題なく、あなたが望んでいることを正確に実行します。もし、別の方法を探しているのであれば、std::find()
/std::find_first_of()
や[std::string::substr()
][3]を使うことができます。
以下はその例です。
#include <iostream>
#include <string>
int main()
{
std::string s("Somewhere down the road");
std::string::size_type prev_pos = 0, pos = 0;
while( (pos = s.find(' ', pos)) != std::string::npos )
{
std::string substring( s.substr(prev_pos, pos-prev_pos) );
std::cout << substring << '\n';
prev_pos = ++pos;
}
std::string substring( s.substr(prev_pos, pos-prev_pos) ); // Last word
std::cout << substring << '\n';
return 0;
}
[3]: http://en.cppreference.com/w/cpp/string/basic_string/substr