c++实现字符串分割

类似于python,shell,perl等语言都提供了方便的split()接口,用以分割字符串。c++/c需要自己写,这样耗时耗力还没效率,没保障的方法,当然是需要避免的。又是强大的boost库提供了方便。

.h文件

#ifndef DIRFILEOPT_HHHH
#define DIRFILEOPT_HHHH

#include <iostream>
#include <vector>
#include <string>

using std::vector;
using std::string;

class CStrOpt
{
private:
	char* m_pStr;
	char m_pattern[10];
public:
	CStrOpt(char*);
	vector<string>& mSplit(vector<string>& vecSplit);
	char* setPattern(char* pPattern);
	~CStrOpt();
};
#endif

.cpp文件

#define _SCL_SECURE_NO_WARNINGS
#include "FileOpt.h"
#include <iterator>
#include <algorithm>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string.hpp>
using namespace std;
using namespace boost::filesystem;
CStrOpt::CStrOpt(char* pStr):
	m_pStr(pStr){
}

char* CStrOpt::setPattern(char* pPattern){                                    //设置分割符
	if(NULL == pPattern)
		return NULL;
	memset(m_pattern,0,sizeof(m_pattern) / sizeof(char));
	memcpy(m_pattern,pPattern,strlen(pPattern));
	return m_pattern;
}
CStrOpt::~CStrOpt(){
	m_pStr = NULL;
}
vector<string>& CStrOpt::mSplit(vector<string>& vecSplit){
	boost::split(vecSplit,m_pStr,boost::is_any_of(m_pattern),boost::token_compress_on); //核心函数 分割字符串m_pStr到vecSplit里面
#ifdef DEBUG
	copy(vecSplit.begin(),vecSplit.end(),ostream_iterator<string>(cout,"\n"));
#endif
	return vecSplit;	
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值