C++用|做分隔符分割字符串
核心函数,握岁把str按照delimiter字符分割,分割结哪宏果存放到容器中。段缓睁
typedef vector<string> str_container_type;
static void split(string const& str, string const& delimiter, str_container_type& dest)
{
size_t pos = 0, found = 0;
while ( found != string::npos )
{
found = str.find(delimiter, pos);
dest.push_back(string(str, pos, found - pos));
pos = found + 1;
}
}
使用示例可以参考这里:
http://ideone.com/gJMEY
用空格分割字符(忽略空格多少)
#define _V(n) * ## (n)
int _tmain(int argc, _TCHAR* argv[])
{
wstring source=_T("0 456 89\\41");
wchar_t sparators=_T('\x20'); /漏陪* space */
size_t start=0; /* read begin */
size_t end=0; /* read count */
wstring dest[3] /* destination */;
size_t index=0; /* index for destination */渣漏
while(true)
{
end = source.find_first_of(sparators,start);
if(wstring::npos==end)
{
_V(dest+index)=source.substr(start,end);
break;/* while(true) */
}
else
{
_V(dest+index++)=source.substr(start,end-start);
start = source.find_first_not_of(sparators,end+1);
}/* if (wstring::npos==end) */
}/* while(true) */
/* test the code */
for each(wstring temp in dest)
wcout<如搜烂<temp<<endl;
getchar();
return NULL;
}/* wmain */
一:对于给唯郑蚂定的字符串str进行遍历;
二:确定筛选条件,符合丛御则添加|分隔符,只是加指埋一个输出;
三:遍历str结束,程序结束。
string a="adf|afadf|fasdfaf|fafasdf|fsdga";
string[] alist = a.Split('|');//alist就是一腔唤个培激数组了配圆袜
具体点行吗?