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
|
#include <iostream>
#include <string>
using std::string;
int charCount(string str, string delim)
{
int size = 0, temp = 0, pos = 0;
while ( (temp = str.find(delim, pos) ) > -1)
{
pos = 1 + temp + delim.length(); size++;
}
return size + 1;
}
string* split(string str, string delim, int& outSize)
{ /* TODO: free this memory when finished!!! */
outSize = charCount(str, delim);
if (outSize == 0)
return NULL;
string* out = new string[outSize];
for (int index = 0, start = 0, find = 0; index < outSize; index++)
{
find = str.find(delim, start);
if (find < 0 || find < start)
{
out[index] = str.substr(start);
break;
}
else
out[index] = str.substr(start, find - start);
start = find + delim.length();
}
return out;
} /* delete [] varName */
string* split(string str, char delim, int& outSize)
{
return split(str, string(1, delim), outSize);
}
int main()
{
int size;
string* test = split("a[]b[]c[]d[]e[]f", "[]", size);
for (int index(0); index < size; index++)
std::cout << test[index] << std::endl;
delete [] test;
return 0;
}
|