blrmaani wrote:
Here is what I want:
string s1 = "This is a list of string";
list<string> s2 = s1.some_method();
Now, I should be able to traverse list s2 and get each
member ( which is of type 'string' ).
I know that this can be achieved using strtok. But I was wondering
if there is any string member function which returns me a list of string?
There's no string member function that returns a list of strings.
Here are two ways to do what you want (assuming you want to tokenize the
string on whitespace):
SOLUTION 1: Use istringstream
#include <algorithm>
#include <iostream>
#include <iterator>
#include <list>
#include <sstream>
#include <string>
int main()
{
std::string s("This is a list of string");
std::istringstream iss(s);
typedef std::istream_iterator<std::string> StringReader;
StringReader first(iss);
StringReader last;
// Initialize a list by reading from iss (implicitly using the
// >> operator)
typedef std::list<std::string> StringList;
StringList myList(first, last);
// Output the contents of the list
typedef std::ostream_iterator<std::string> StringWriter;
std::copy (myList.begin(), myList.end(),
StringWriter(std::cout, "\n"));
}
Here's the output:
This
is
a
list
of
string
SOLUTION 2: Use boost::tokenizer
This is a bit off-topic for this newsgroup, since it involves a
non-standard library. But you might be interested in using the Boost
library's tokenizer template (see
http://www.boost.org/).
#include <algorithm>
#include <iostream>
#include <iterator>
#include <list>
#include <string>
#include <boost/tokenizer.hpp>
int main()
{
// Make a tokenizer object from a string (tokenized on
// whitespace)
std::string s("This is a list of string");
boost::tokenizer<> tokens(s);
// Create a list from the tokens
typedef std::list<std::string> StringList;
StringList myList(tokens.begin(), tokens.end());
// Output the contents of the list
typedef std::ostream_iterator<std::string> StringWriter;
std::copy (myList.begin(), myList.end(),
StringWriter(std::cout, "\n"));
}
The output:
This
is
a
list
of
string
Hope that helps.
Regards,
Russell Hanneken
rg********@pobox.com
Remove the 'g' from my address to send me mail.