您的位置:首页 > 编程语言 > C语言/C++

C++分割字符串

2012-08-07 08:35 429 查看
最近看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;

}

运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: