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())
{
}
}
}
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
.
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";
}
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 :)
精彩评论