split函数是一个非常常用的函数,在Java等高级语言中都很常见,但是在标准C++中却没有,这不禁让人有些遗憾,虽然像boost等第三方库或者所谓的准标准库中已经实现了相关相关函数,但是为了这么简单的功能把庞大的函数库部署好,则是没必要的。这里提供split的一个简单实现,分string和wstring
string:
void split(vector<string> &Result, string &Input,const char* Regex)
{
int pos = 0;
int npos = 0;
int regexlen = strlen(Regex);
while((npos=Input.find(Regex, pos))!=-1)
{
string tmp = Input.substr(pos,npos-pos);
Result.push_back(tmp);
pos = npos+regexlen;
}
Result.push_back(Input.substr(pos,Input.length()-pos));
}
wstring
void split(vector<wstring> &Result, wstring &Input,const wchar_t* Regex)
{
int pos = 0;
int npos = 0;
int regexlen = wcslen(Regex);
while((npos=Input.find(Regex, pos))!=-1)
{
wstring tmp = Input.substr(pos,npos-pos);
Result.push_back(tmp);
pos = npos+regexlen;
}
Result.push_back(Input.substr(pos,Input.length()-pos));
}
这用用到了标准库的string wstring 同时还要使用命名空间std