CPP中字符串分割函數,split

cpp的標準庫函數中沒有字符串分割函數,而這個函數又是經常需要用到的,有必要寫出一個模板,背會以便使用

void split(string str,vector<string> &v,string spacer)
{
    int pos1,pos2;
    int len=spacer.length();     //記錄分隔符的長度
    pos1=0;
    pos2=str.find(spacer);
    while( pos2 != string::npos )
    {
        v.push_back( str.substr(pos1,pos2-pos1) );
        pos1 = pos2 + len;
        pos2 = str.find(spacer,pos1);    // 從str的pos1位置開始搜尋spacer
    }
    if(pos1 != str.length()) //分割最後一個部分
       v.push_back(str.substr(pos1));
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章