This one is based on some code i found at
www.codeproject.com years
ago. I extended it for more flexibility. This version now supports wide
character strings and any STL container type and most string
classes(STL string, MFC/ATL CString, etc. The only requirement for the
string class is a constructor that accepts a C style string pointer).
You can use it like this:
#include "split.h"
....
const char* a = "aaa bbb cccc";
list<string> results; // or vector<string> results;
split(a, " ", results);
---->8---->8---->8---->8---->8---->8---->8---->8---->8---->8---->8---->8----
// split.h
#pragma once
#include <cstring>
template<typename CharType>
class SplitCharTraits
{
public:
static size_t __cdecl length(const CharType* s)
{
return std::char_traits<CharType>::length(s);
}
static char* strstr(const char* string, const char* strSearch)
{
return std::strstr(string, strSearch);
}
static wchar_t* strstr(const wchar_t* string, const wchar_t*
strSearch)
{
return std::wcsstr(string, strSearch);
}
};
template<typename CharType, typename ContainerType>
int split(const CharType* str, const CharType* delim,
ContainerType& results, bool empties = true)
{
typedef typename ContainerType::value_type StrType;
CharType* pstr = const_cast<CharType*>(str);
CharType* r = NULL;
r = SplitCharTraits<CharType>::strstr(pstr, delim);
int dlen = SplitCharTraits<CharType>::length(delim);
while( r != NULL ) {
CharType* cp = new CharType[(r-pstr)+1];
memcpy(cp, pstr, sizeof(CharType)*(r-pstr));
cp[(r-pstr)] = 0;
if( SplitCharTraits<CharType>::length(cp) > 0 || empties )
results.push_back(StrType(cp));
delete[] cp;
pstr = r + dlen;
r = SplitCharTraits<CharType>::strstr(pstr, delim);
}
if( SplitCharTraits<CharType>::length(pstr) > 0 || empties )
results.push_back(StrType(pstr));
return results.size();
}