snippetcppCritical
How do I iterate over the words of a string?
Viewed 0 times
howtheoveriteratewordsstring
Problem
How do I iterate over the words of a string composed of words separated by whitespace?
Note that I'm not interested in C string functions or that kind of character manipulation/access. I prefer elegance over efficiency. My current solution:
Note that I'm not interested in C string functions or that kind of character manipulation/access. I prefer elegance over efficiency. My current solution:
#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);
}Solution
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.
Instead of copying the extracted tokens to an output stream, one could insert them into a container, using the same generic
... or create the
#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{}};Code Snippets
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
int main() {
using namespace std;
string sentence = "And I feel fine...";
istringstream iss(sentence);
copy(istream_iterator<string>(iss),
istream_iterator<string>(),
ostream_iterator<string>(cout, "\n"));
}vector<string> tokens;
copy(istream_iterator<string>(iss),
istream_iterator<string>(),
back_inserter(tokens));vector<string> tokens{istream_iterator<string>{iss},
istream_iterator<string>{}};Context
Stack Overflow Q#236129, score: 1513
Revisions (0)
No revisions yet.