C++分割字符串

最近看C++ primer 的string相关章节,了解到了 find_first_of这个函数。这个函数有四个重载函数。具体的函数形参就不多做解释了。C++primer 或者谷歌或者百度都能找到答案。

下面用find_first_of 和 substr 这两个函数来实现分割字符串的功能:

//参数说明:str 为待分割的字符串, split 为分割字符串,vStr存在分割后的字符串

void stringSplit(string str, string split, vector<string > &vStr)
{
string::size_type pos = 0;
string::size_type numBegin = 0;
str += split.substr(0,1);    //确保待分割的字符串末尾有分隔符
while((pos = str.find_first_of(split, pos))!= string::npos )
{
if( pos!= 0 && string::npos == str.substr(pos - 1, 1).find_first_of(split))
{
vStr.push_back(str.substr(numBegin, pos - numBegin ));
}
++pos;
numBegin = pos;
}
}

下面是一个例子:

#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>

using namespace std;

void stringSplit(string str, string split, vector<string > &vStr)
{
string::size_type pos = 0;
string::size_type numBegin = 0;
str += split.substr(0,1);    //确保待分割的字符串末尾有分隔符
while((pos = str.find_first_of(split, pos))!= string::npos )
{
if( pos!= 0 && string::npos == str.substr(pos - 1, 1).find_first_of(split))
{
vStr.push_back(str.substr(numBegin, pos - numBegin ));
}
++pos;
numBegin = pos;
}
}

int _tmain(int argc, _TCHAR* argv[])
{
string str = "my name is<hello,word> : test[string](string.)world";
string split = " ,;:!?.<>[]()""'";
vector<string > vStr;
stringSplit(str, split, vStr);
for(vector<string>::iterator it = vStr.begin(); it != vStr.end(); ++it)
{
  cout << *it <<endl;
}
return 0;
}

运行结果:



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值