1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
|
#include <vector>
#include <string>
#define TSTRING std::basic_string<T, std::char_traits<T>, std::allocator<T>>
#define SSPLIT_STATE_NORMAL 0
#define SSPLIT_STATE_GROUP 1
#define SSPLIT_STATE_ESCAPE 2
template <class T>
std::vector<TSTRING> smartSplit(const TSTRING& str, const T delim, const T gStart, const T gStop, const T escape)
{
std::vector<TSTRING> v;
TSTRING a;
TSTRING::const_iterator i = str.begin();
TSTRING::const_iterator e = str.end();
int state = SSPLIT_STATE_NORMAL;
for(; i != e; ++i)
{
switch(state)
{
case SSPLIT_STATE_NORMAL:
if (*i == delim)
{
if(a.size())
{
v.push_back(a);
a.clear();
}
}
else if (*i == gStart)
{
state = SSPLIT_STATE_GROUP;
}
else if (*i == escape)
{
state = SSPLIT_STATE_ESCAPE;
}
else
{
a.push_back(*i);
}
break;
case SSPLIT_STATE_GROUP:
if(*i == escape)
{
state += SSPLIT_STATE_ESCAPE;
}
else if(*i == gStop)
{
if(a.size())
{
v.push_back(a);
a.clear();
}
state = SSPLIT_STATE_NORMAL;
}
else
{
a.push_back(*i);
break;
}
break;
case SSPLIT_STATE_ESCAPE:
case SSPLIT_STATE_ESCAPE | SSPLIT_STATE_GROUP:
a.push_back(*i);
state -= SSPLIT_STATE_ESCAPE;
break;
}
}
if(a.size()) v.push_back(a);
return v;
} |