A simple implementation of string split in C++

Since string's split function is not naturally provided in C++, we must implement it by ourselves. Here is a simple implementation of split based on strtok.

vector<string> split(const string &str, const string &sep)
{
	char *cstr = new char[str.size()+1]; 
	char *csep = new char[sep.size()+1];
	strcpy(cstr, str.c_str());
	strcpy(csep, sep.c_str());
	char *csubstr = strtok(cstr, csep);
	vector<string> res;
	while (csubstr != NULL)
	{
		res.push_back(csubstr);
		csubstr = strtok(NULL, csep);
	}
	delete[] cstr;
	delete[] csep;
	return res;
}
To successfully use it, please include following headers:

#include <vector>  // necessary for split, vector
#include <string>  // necessary for split, string
#include <cstring>  // necessary for split, strcpy, strtok



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章