C++學習:字符串分割函數

C++實現字符串分割有多種方式,個人認爲下面這種實現比較科學:

template<typename StrType>
void SplitString(const StrType& strSourceString, const StrType& strSeperator, std::vector<StrType>& vecResult)
{
    StrType::size_type pos1 = 0, pos2 = strSourceString.find(strSeperator);
    while (StrType::npos != pos2)
    {
        if (pos2 != pos1)
        {
            vecResult.push_back(s.substr(pos1, pos2 - pos1));
        }

        pos1 = pos2 + strSeperator.size();
        pos2 = strSourceString.find(strSeperator, pos1);
    }

    if (pos1 != strSourceString.length())
    {
        vecResult.push_back(strSourceString.substr(pos1));
    }
}

可根據需要生成std::string或std::wstring版本。

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