实现用指定的分隔符把一个字符串分解成多个字符串,并把结果保存到一个vector中。
示例:
输入:
8:00起售车站:北京西、南京、南京南、同江
输出:
北京西
南京
南京南
同江
#include <iostream>
#include <vector>
#include <string>
using namespace std;
/********
vecStr: 用于存储结果的vector
strSource: 被分解的字符串
strSplit: 分隔符
nSkip: 开头忽略的字符数目,默认为0
********/
void SplitStringToVector( vector<string> &vecStr, string strSource, string strSplit, int nSkip = 0 )
{
vector<string>::size_type sPos = nSkip;
vector<string>::size_type ePos = strSource.find( strSplit, sPos );
while( ePos != string::npos )
{
if( sPos != ePos ) vecStr.push_back( strSource.substr( sPos, ePos - sPos ) );
sPos = ePos + strSplit.size();
ePos = strSource.find( strSplit, sPos );
}
if( sPos < strSource.size() ) vecStr.push_back( strSource.substr( sPos, strSource.size() - sPos ) );
}
int main()
{
string str1 = "8:00起售车站:北京西、南京、南京南、同江";
vector<string> vecStr;
SplitStringToVector( vecStr, str1, "、", 13 );
for( vector<string>::iterator iter = vecStr.begin(); iter != vecStr.end(); iter++ )
cout<<*iter<<endl;
return 0;
}