String Split

String Split

Tans 961 2021-01-06

因为C++没有现成的字符串分割模板,提供几个字符串分割模板以供查阅。

一、自己实现

//自己写的
vector<string> split(const string &str, char &flag){
    int i = 0, j = 0;
    vector<string> ans;
    while(i < str.length() and j < str.length()){
        while(i < str.length() and str[i] == flag) i++;
        j = i;
        while(j < str.length() and str[j] != flag) j++;
        if(i < str.length()) ans.push_back(str.substr(i, j - i););
        i = j;
    }
    return ans;
}

二、通过fox

stringstream实现

需要包含sstream头文件

vector<string> split3(const string &str, const char pattern){
    vector<string> res;
    stringstream input(str);   //读取str到字符串流中
    string temp;
    //使用getline函数从字符串流中读取,遇到分隔符时停止,和从cin中读取类似
    //注意,getline默认是可以读取空格的
    while(getline(input, temp, pattern)) res.push_back(temp);
    return res;
}

三、通过Substr实现

vector<string> split(const string &str, const string &pattern)
{
    vector<string> res;
    if(str == "")
        return res;
    //在字符串末尾也加入分隔符,方便截取最后一段
    string strs = str + pattern;
    size_t pos = strs.find(pattern);

    while(pos != strs.npos)
    {
        string temp = strs.substr(0, pos);
        res.push_back(temp);
        //去掉已分割的字符串,在剩下的字符串中进行分割
        strs = strs.substr(pos+1, strs.size());
        pos = strs.find(pattern);
    }

    return res;
}