C++中string字符串分割實現

C++標準庫裏面沒有提供的字符分割函數split ,需要自己編寫。

C++中string字符串分割實現

#include <vector>
#include <string>
#include <iostream>
using namespace std;

std::vector<std::string> split(const std::string& str, const std::string& delim)
{
    std::vector<std::string> res;
    if ("" == str) 
        return res;
    //先將要切割的字符串從string類型轉換爲char*類型  
    char * strs = new char[str.length() + 1];  
    strcpy(strs, str.c_str());

    char * d = new char[delim.length() + 1];
    strcpy(d, delim.c_str());

    char *p = strtok(strs, d);
    while (p) {
        std::string s = p; //分割得到的字符串轉換爲string類型  
        res.push_back(s); //存入結果數組  
        p = strtok(NULL, d);
    }

    return res;
}


int main()
{
    string s = "a,b,c,d,e,f";
    vector<string> v;
    v = split(s,","); //可按多個字符來分隔;
    for(vector<string>::size_type i = 0; i != v.size(); ++i)
        cout << v[i] << " ";
    cout << endl;  
}

//輸出: a b c d e f

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章