參考:http://www.cnblogs.com/oomusou/archive/2009/05/09/c_split.html
wstrings split(const wchar_t *str, const wchar_t *del )
{
int len = wcslen(str);
std::vector<wchar_t> tstr;
tstr.resize(len+1);
wcscpy(&tstr[0], str);
wstrings strs;
wchar_t *s = wcstok(&tstr[0], del);
while(s != NULL) {
strs.push_back(s);
s = wcstok(NULL, del);
}
return strs;
}
strings split(const char *str, const char *del )
{
int len = strlen(str);
std::vector<char> tstr;
tstr.resize(len+1);
strcpy(&tstr[0], str);
strings strs;
char *s = strtok(&tstr[0], del);
while(s != NULL) {
strs.push_back(s);
s = strtok(NULL, del);
}
return strs;
}
測試碼
strings ss = split("10,-20,-30", ",");
for (int i=0;i<ss.size();i++)
{
std::cout << ss[i] << std::endl;
}
修改後
strings split(const char *str, const char *del )
{
int len = strlen(str),
dlen = strlen(del),
lastindex = 0,
index = 0;
strings strs;
std::string tstr;
tstr.reserve(128);
int i;
for (i=0;i<len;i++)
{
for (int j=0;j<dlen;j++)
{
if (del[j] == str[i])
{
if (i-lastindex > 1)
{
tstr.assign(str+lastindex, str+i);
strs.push_back(tstr);
lastindex = i+1;
}
else
{
lastindex = i+1;
}
}
}
}
tstr.assign(str+lastindex, str+i);
strs.push_back(tstr);
return strs;
}
測試碼
strings ss2 = split("40,-50 -60.-70", ", .");
for (int i=0;i<ss2.size();i++)
{
std::cout << ss2[i] << std::endl;
}
留言列表