Split a char array by delimiter in C++

There are a few ways to accomplish this.

//..
char* buffer = "this*is*a*simple*test";
string delimiter = "*";
string s(buffer);
size_t pos = 0;
string token;
while ((pos = s.find(delimiter)) != std::string::npos) {
	token = s.substr(0, pos);
	cout<<token<<endl;
	s.erase(0, pos + delimiter.length());
}
cout<<s<<endl;
//..

Prints

this
is
a
simple
test

 

//..
char* buffer = "this*is*a*simple*test";
char* s;
s = strtok (buffer ,"*");
while (s != NULL)
{
	printf ("%sn",s);
	s = strtok (NULL, "*");
}
//..

Prints

this
is
a
simple
test

 

Categories: C++ Tags: , , , ,
%d bloggers like this: