c++ - Most elegant way to split a string? -


what's elegant way split 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: " << substr << endl;     } while (iss);      return 0; } 

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

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -