首页 > 代码库 > stl string 使用指定的分隔符分割成数个子字符串

stl string 使用指定的分隔符分割成数个子字符串

#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std;void StringSplit(const string& str,vector<string>& vStr,const char& division){	int startPos = 0;	int endPos = string::npos;			startPos = str.find_first_not_of(division);	while(startPos != string::npos)	{		endPos = str.find_first_of(division,startPos);		if(endPos != string::npos)		{			string strSplit = str.substr(startPos,(endPos-startPos));			vStr.push_back(strSplit);		}else		{			string strSplit = str.substr(startPos);			vStr.push_back(strSplit);		}		startPos = str.find_first_not_of(division,endPos );	}	return;}void PrintElement(const string& str){	cout << str << endl;}int _tmain(int argc, _TCHAR* argv[]){	string str1 = "_1_dfg45d#$__123456789_1_dfg45d#$__123456789_1_dfg45d#$__123456789_1_dfg45d#$__123456789_1_dfg45d#$__123456789";	string str2 = "__sdfsf_dfg45d#$__张三李四____sdfsf_dfg45d#$__张三李四____sdfsf_dfg45d#$__张三李四____sdfsf_dfg45d#$__张三李四__";	string str3 = "(*^(*^(*_dfg45d#$__天天向上__(*^(*^(*_dfg45d#$__天天向上__(*^(*^(*_dfg45d#$__天天向上__(*^(*^(*_dfg45d#$__天天向上__";	vector<string> vStr;	StringSplit(str1,vStr,‘_‘);	for_each(vStr.begin(),vStr.end(),PrintElement);	cout << endl;	vStr.clear();	StringSplit(str2,vStr,‘_‘);	for_each(vStr.begin(),vStr.end(),PrintElement);	cout << endl;	vStr.clear();	StringSplit(str3,vStr,‘_‘);	for_each(vStr.begin(),vStr.end(),PrintElement);	cout << endl;	vStr.clear();	return 0;}