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



A simple implementation of string split in C++

上一篇:Spark学习计划


下一篇:linshi_temp_erweima_html_backup