Thursday, November 22, 2018

c++ - How do I iterate over the words of a string?



I'm trying to iterate over the words of a string.



The string can be assumed to be composed of words separated by whitespace.



Note that I'm not interested in C string functions or that kind of character manipulation/access. Also, please give precedence to elegance over efficiency in your answer.



The best solution I have right now is:




#include 
#include
#include

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);
}



Is there a more elegant way to do this?


Answer



For what it's worth, here's another way to extract tokens from an input string, relying only on standard library facilities. It's an example of the power and elegance behind the design of the STL.



#include 
#include
#include
#include
#include


int main() {
using namespace std;
string sentence = "And I feel fine...";
istringstream iss(sentence);
copy(istream_iterator(iss),
istream_iterator(),
ostream_iterator(cout, "\n"));
}



Instead of copying the extracted tokens to an output stream, one could insert them into a container, using the same generic copy algorithm.



vector tokens;
copy(istream_iterator(iss),
istream_iterator(),
back_inserter(tokens));


... or create the vector directly:




vector tokens{istream_iterator{iss},
istream_iterator{}};

No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...