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<typena me CharType>
class SplitCharTraits
{
public:
static size_t __cdecl length(const CharType* s)
{
return std::char_trait s<CharType>::le ngth(s);
}
static char* strstr(const char* string, const char* strSearch)
{
return std::strstr(str ing, strSearch);
}
static wchar_t* strstr(const wchar_t* string, const wchar_t*
strSearch)
{
return std::wcsstr(str ing, strSearch);
}
};
template<typena me 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<Char Type*>(str);
CharType* r = NULL;
r = SplitCharTraits <CharType>::str str(pstr, delim);
int dlen = SplitCharTraits <CharType>::len gth(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>::len gth(cp) > 0 || empties )
results.push_ba ck(StrType(cp)) ;
delete[] cp;
pstr = r + dlen;
r = SplitCharTraits <CharType>::str str(pstr, delim);
}
if( SplitCharTraits <CharType>::len gth(pstr) > 0 || empties )
results.push_ba ck(StrType(pstr ));
return results.size();
}