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::istringstr eam iss(s);
typedef std::istream_it erator<std::str ing> 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_it erator<std::str ing> StringWriter;
std::copy (myList.begin() , myList.end(),
StringWriter(st d::cout, "\n"));
}
Here's the output:
This
is
a
list
of
string
SOLUTION 2: Use boost::tokenize r
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::tokenize r<> tokens(s);
// Create a list from the tokens
typedef std::list<std:: string> StringList;
StringList myList(tokens.b egin(), tokens.end());
// Output the contents of the list
typedef std::ostream_it erator<std::str ing> StringWriter;
std::copy (myList.begin() , myList.end(),
StringWriter(st d::cout, "\n"));
}
The output:
This
is
a
list
of
string
Hope that helps.
Regards,
Russell Hanneken
rg********@pobo x.com
Remove the 'g' from my address to send me mail.