c++ - The most elegant way to iterate the words of a string -


what elegant way iterate words of string? string can assumed composed of words separated whitespace.

note i'm not interested in c string functions or kind of character manipulation/access. also, please give precedence elegance on efficiency in answer.

the best solution have right is:

#include <iostream> #include <sstream> #include <string>  using namespace std;  int main() {     string s = "somewhere down road";     istringstream iss(s);          {         string subs;         iss >> subs;         cout << "substring: " << subs << endl;     } while (iss); } 

for it's worth, here's way extract tokens input string, relying on standard library facilities. it's example of power , elegance behind design of stl.

#include <iostream> #include <string> #include <sstream> #include <algorithm> #include <iterator>  int main() {     using namespace std;     string sentence = "and feel fine...";     istringstream iss(sentence);     copy(istream_iterator<string>(iss),          istream_iterator<string>(),          ostream_iterator<string>(cout, "\n")); } 

instead of copying extracted tokens output stream, 1 insert them container, using same generic copy algorithm.

vector<string> tokens; copy(istream_iterator<string>(iss),      istream_iterator<string>(),      back_inserter(tokens)); 

... or create vector directly:

vector<string> tokens{istream_iterator<string>{iss},                       istream_iterator<string>{}}; 

Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -