以指定分隔符分割字符串存储到vector中

来源:互联网 发布:淘宝回购加不加权重 编辑:程序博客网 时间:2024/03/28 18:03
        实现用指定的分隔符把一个字符串分解成多个字符串,并把结果保存到一个vector中。

示例:
输入:
8:00起售车站:北京西、南京、南京南、同江

输出:
北京西
南京
南京南
同江

#include <iostream>#include <vector>#include <string>using namespace std;/********vecStr: 用于存储结果的vectorstrSource: 被分解的字符串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;   }



0 0
原创粉丝点击