tags:

views:

579

answers:

5

Hi

I have a string "stack+ovrflow*newyork;" i have to split this stack,overflow,newyork

any idea??

+2  A: 

You can use _tcstok to tokenize the string based on a delimiter.

Naveen
What's the difference between _tcstok and strtok?
Wadih M.
It will call either strtok or wcstok depnding on whether UNICODE compiler flag is set or not during compliation.
Naveen
+7  A: 

You have a couple of options:

You can use C++ std::strings and parse them using a stringstream and getline (safest way)

std::string str = "stack+overflow*newyork;";
std::istringstream stream(str);
std::string tok1;
std::string tok2;
std::string tok3;

std::getline(stream, tok1, '+');
std::getline(stream, tok2, '*');
std::getline(stream, tok3, ';');

std::cout << tok1 << "," << tok2 << "," << tok3 << std::endl

Or you can use one of the strtok family of functions (see Naveen's answer for the unicode agnostic version), if you are comfortable with char pointers

char str[30]; 
strncpy(str, "stack+overflow*newyork;", 30);

// point to the delimeters
char* result1 = strtok(str, "+");
char* result2 = strtok(str, "*");
char* result3 = strtok(str, ";");

// replace these with commas
if (result1 != NULL)
{
   *result1 = ',';
}
if (result2 != NULL)
{
   *result2 = ',';
}

// output the result
printf(str);
Doug T.
+1 nice comparison of getline and strtok approach
Faisal Vali
when using strtok, beware of it's single-theadedness!
xtofl
+4  A: 

See boost tokenizer here.

Cătălin Pitiș
boost tokenizer's got to get an up vote ;)
Faisal Vali
+2  A: 

This site has a string tokenising function that takes a string of characters to use as delimiters and returns a vector of strings.

Simple STL String Tokenizer Function

Salgar
+3  A: 

Boost tokenizer

Simple like this:

#include <boost/tokenizer.hpp>
#include <vector>
#include <string>
std::string stringToTokenize= "stack+ovrflow*newyork;";
boost::char_separator<char> sep("+*;");
boost::tokenizer< boost::char_separator<char> > tok(stringToTokenize, sep);
std::vector<std::string> vectorWithTokenizedStrings;
vectorWithTokenizedStrings.assign(tok.begin(), tok.end());

Now vectorWithTokenizedStrings has the tokens you are looking for. Notice the boost::char_separator variable. It holds the separators between the tokens.

Edison Gustavo Muenz