首页 > 编程语言 > 详细

A simple implementation of string split in C++

时间:2014-02-25 12:47:22      阅读:337      评论:0      收藏:0      [点我收藏+]

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++

原文:http://blog.csdn.net/jsc0218/article/details/19818537

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!