Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to understand strtok

Tags:

c++

strtok

Consider the following snippet that uses strtok to split the string madddy.

char* str = (char*) malloc(sizeof("Madddy"));
strcpy(str,"Madddy");

char* tmp = strtok(str,"d");
std::cout<<tmp;

do
{
    std::cout<<tmp;
    tmp=strtok(NULL, "dddy");
}while(tmp!=NULL);

It works fine, the output is Ma. But by modifying the strtok to the following,

tmp=strtok(NULL, "ay");

The output becomes Madd. So how does strtok exactly work? I have this question because I expected strtok to take each and every character that is in the delimiter string to be taken as a delimiter. But in certain cases it is doing that way but in few cases, it is giving unexpected results. Could anyone help me understand this?

like image 952
Karthick Avatar asked Dec 05 '22 23:12

Karthick


1 Answers

"Trying to understand strtok" Good luck!

Anyway, we're in 2011. Tokenise properly:

std::string str("abc:def");
char split_char = ':';
std::istringstream split(str);
std::vector<std::string> token;

for (std::string each; std::getline(split, each, split_char); token.push_back(each));

:D

like image 102
Lightness Races in Orbit Avatar answered Dec 09 '22 14:12

Lightness Races in Orbit