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

本文介绍了一个 C++ 模板类 `spliteVectorImp` 的实现,该类可以将带有指定分隔符的字符串分割并转换成整数向量。通过实例演示了如何使用该类处理不同格式的字符串数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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;
}

测试效果 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值