473,749 Members | 2,451 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

STL: Converting a string into a list of string

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?

thanks in advance
blrmaani
Jul 22 '05 #1
4 9113
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.
Jul 22 '05 #2
On 27 Apr 2004 12:02:51 -0700 in comp.lang.c++, bl******@yahoo. com
(blrmaani) wrote,
string s1 = "This is a list of string";
list<string> s2 = s1.some_method( );


I would do that using a quickie tokenizer template function such as
http://groups.google.com/gr*********....earthlink.net

Jul 22 '05 #3
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?

thanks in advance
blrmaani


http://linuxselfhelp.com/HOWTO/C++Pr...g-HOWTO-7.html.

HTH
--
Karthik

Humans please 'removeme_' for my real email.
Jul 22 '05 #4
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' ).
Why do you want a list vs. a vector?
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 nothing built-in. You can do it yourself by creating a strstream
from the original string and reading in each substring. Alternatively,
I'll give you the Explode() routine I wrote, which works basically like
the one in PHP. I'll leave it as an exercise for you to change it from
vector to list if you are set on that.
#include <vector>
#include <string>

// breaks apart a string into substrings separated by a character string
// does not use a strtok() style list of separator characters
// returns a vector of std::strings

std::vector<std ::string> Explode (const std::string &inString,
const std::string &separator)
{
std::vector<std ::string> returnVector;
std::string::si ze_type start = 0;
std::string::si ze_type end = 0;

while ((end = inString.find (separator, start)) != std::string::np os)
{
returnVector.pu sh_back (inString.subst r (start, end-start));
start = end + separator.size( );
}

returnVector.pu sh_back (inString.subst r (start));

return returnVector;
Brian Rodenborn
Jul 22 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
1414
by: Michael | last post by:
Guys, I'm trying to compile this code to build a huffman tree, but I'm getting a runtime error and my degugger ends up somewhere in the STL files. What am i doing wrong. I appreciate its not effiecient/stylistic, etc, it was just something i wanted to try Thanks Mike
10
15131
by: Der Andere | last post by:
I need to implement a sorted (ordered) list. STL has no sorted list type as far as I know. Is there a (straight) way to implement a sorted list using STL? BTW: The type of items in the list will be a class. Is it necessary to implement the > or < operators or to write a compare-function that returns the larger or smaller of two classes? Ideally, the list begins with the smallest element. Cheers, Matthias
6
8860
by: Alex Gerdemann | last post by:
Hello, I am writing a program where I have a vector (std::vector<std:string> list) that I need to search many times. To accomplish this efficiently, I plan to sort the list using std::sort(list.begin(),list.end()), then run binary searches. I need to get the indices of the elements found so I can construct a matrix where I allocate a row of a matrix for each string in the list (row one for the first item in the list, etc). However...
7
3254
by: Tony Johansson | last post by:
Hello!! Assume I have a handle body pattern with classes called Handle and Body. In the Body class I store one int value for example 7 or some other integer value. In the Handle class I have a pointer to the Body class. If a want to create a STL container of List with the following declaration List <Handle <Body> > list
0
1472
by: Tony Johansson | last post by:
Hello! I have two classes called Handle which is a template class and a class Integer which is not a template class. The Integer class is just a wrapper class for a primitive int with some methods. I don't show the Integer class because it will not add any information to my problem. Main is using some STL function. In main you put in nodes in the STL list and you can display the STL list and other things such as erase some value from...
7
1784
by: Sammy | last post by:
Its slow but Im in the process of converting some of my admittedly ugly code into STL. At the moment Im working to change a mess that I like to call a linked list when Im in a generous mood. Actually it works, but could be much better. When using the STL list (made up of simple pointers), I assume using the erase function does not automatically destroy the objects they point to... just the pointer itself. Is this so? If it is... will...
2
1882
by: Bruce | last post by:
I am converting a DLL project from VC7 to VC8. The project is a managed C++ DLL. The project uses a non managed C++ library compiled an linked in VC7 which uses the STL. I just about got everything to link with the exception of some STL link errors. Here is an example of one of the errors:
3
3479
by: misu101 | last post by:
Hi, I have an application that defines a hash_set as: typedef hash_set<const char*, hash<const char*>, chunker_eqstr> StringSet; This code compiles OK with VS6 and SGI STL library. It is patterned after the SGI STL documentations. We are now moving to VS 2005 and the SGI STL header file is in conflict with the VS 2005 system header files. But when I try to use VS 2005 and the VS8 STL library instead of SGI STL, I got these error...
7
3129
by: ademirzanetti | last post by:
Hi there !!! I would like to listen your opinions about inherit from a STL class like list. For example, do you think it is a good approach if I inherit from list to create something like "myList" as in the example below ? #include "Sector.h" using namespace boost;
0
8833
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9568
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9389
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9335
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9256
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6801
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4881
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3320
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2794
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.