2

Possible Duplicate:
C++: How to split a string?

Hi friends,i need to split a string containing comma seperated values and have to store each value to a variable to use further in the program.I have my code as following : but i am getting error in my code :

string myString = ........// i am getting the string from a function
string::iterator it = myString .begin();
while ( it != myString .end() )
 {
      if ( *it == ',' ) 
         {
           string element =*it++; //i can't do such type of conversion.but then how can 
                                    i get each value ?
           if(element.empty())
             {
             }
         } 
 }
Community
  • 1
  • 1
vidhya
  • 2,861
  • 5
  • 28
  • 28
  • 1
    See the answers to this question instead of implementing it again: http://stackoverflow.com/questions/236129/c-how-to-split-a-string – Naveen May 04 '11 at 10:44
  • @Naveen: and more precisely, Feruccio's excellent answer http://stackoverflow.com/questions/236129/c-how-to-split-a-string/236234#236234 --> tokenize using iterators is cheap! – Matthieu M. May 04 '11 at 12:02

3 Answers3

4

I would recommend using some available library as the boost string utilities http://www.boost.org/doc/libs/1_46_1/doc/html/string_algo.html

If you need to implement it manually, I would not use iterators, but rather std::string::find to obtain the start and end positions of each one of the elements and then std::string::substr.

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489
1

You can simply do as following

#include <iostream>
#include <sstream>
#include <string>

std::string String = "Your,String,is,here";
char Separator = ',';

std::istringstream StrStream(String);
std::string Token;

while(std::getline(StrStream, Token, Separator))
{
  std::cout << Token << "\n";
}
Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
sarat
  • 10,512
  • 7
  • 43
  • 74
0

Previously answered here,

C++ ostream out manipulation

I do think there must be even more elegant solutions around here on SO, but this one at least includes unit tests :)

Community
  • 1
  • 1
sehe
  • 374,641
  • 47
  • 450
  • 633