现在的位置: 首页 > 综合 > 正文

使用vector和strchr快速分割字符串

2013年07月31日 ⁄ 综合 ⁄ 共 1274字 ⁄ 字号 评论关闭
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <vector>
using namespace std;
#include <string.h>
#include <intsafe.h>

template<typename CharType,typename EleType
	,typename SpliteEleFunType,SpliteEleFunType SpliteEleFun
	,EleType(__cdecl*ToEleFun)(const CharType*) >
class spliteVectorImp:public std::vector<EleType>
{
public:
	spliteVectorImp(const CharType* lpszData,const CharType c, size_t nMayMaxCount=100)
	{
		__super::reserve(nMayMaxCount);
		for(CharType *str = (CharType*)lpszData;str && *str;)
		{
			if(*str != c)push_back(ToEleFun(str));
			if(str = SpliteEleFun(str,c))++str;
		}
	}
};
typedef spliteVectorImp<char	,int,char*(__CRTDECL*)(char*,int),			::strchr,::atoi> spliteIntVectorA;
typedef spliteVectorImp<wchar_t	,int,wchar_t*(__CRTDECL*)(wchar_t*,wchar_t),::wcschr,::_wtoi> spliteIntVectorW;
#ifdef _UNICODE
	typedef spliteIntVectorW spliteIntVector;
#else
	typedef spliteIntVectorA spliteIntVector;
#endif
int _tmain(int argc, _TCHAR* argv[])
{
	const TCHAR sz2[][26] = 
	{
		_T(""),_T("#"),_T("%"),
		_T("123"),_T("123#"),_T("123#456"),_T("123#456#")
		,_T("123#456#789"),_T("123#456#789##"),_T("###123#456#789##"),_T("###123#456+789##88")
	};
	for (int i(0);i<_countof(sz2);++i)
	{
		auto &sz = sz2[i];
		wcout<<L"-----------["<<sz <<L"]-----------"<< endl;
		spliteIntVector v(sz,_T('#'),100);
		for (auto pos = v.begin(); pos!=v.end();++pos)
		{
			cout << (*pos) << endl;
		}
	}
	return 0;
}

测试效果 

抱歉!评论已关闭.