日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C++11實現字符串分割的示例_C 語言

作者:Mr_John_Liang ? 更新時間: 2022-04-07 編程語言

C++11 字符串分割代碼示例如下,很顯然, 使用了C++11 特性,代碼簡潔好多

#include <iostream>
#include <string>
#include <vector>
#include <regex>
?
using namespace std;
?
//沒有使用C++11特性
vector<string> testSplit(string srcStr, const string& delim)
{
?? ?int nPos = 0;
?? ?vector<string> vec;
?? ?nPos = srcStr.find(delim.c_str());
?? ?while(-1 != nPos)
?? ?{
?? ??? ?string temp = srcStr.substr(0, nPos);
?? ??? ?vec.push_back(temp);
?? ??? ?srcStr = srcStr.substr(nPos+1);
?? ??? ?nPos = srcStr.find(delim.c_str());
?? ?}
?? ?vec.push_back(srcStr);
?? ?return vec;
}
?
//使用C++11特性
vector<string> testSplit11(const string& in, const string& delim)
{
? ? vector<string> ret;
? ? try
? ? {
? ? ? ? regex re{delim};
? ? ? ? return vector<string>{
? ? ? ? ? ? ? ? sregex_token_iterator(in.begin(), in.end(), re, -1),
? ? ? ? ? ? ? ? sregex_token_iterator()
? ? ? ? ? ?}; ? ? ?
? ? }
? ? catch(const std::exception& e)
? ? {
? ? ? ? cout<<"error:"<<e.what()<<std::endl;
? ? }
? ? return ret;
}
?
int main()
{
?? ?vector<string>ret = testSplit("how many credits ?", " ");
?? ?for(int i = 0 ; i < ret.size(); ++i)
?? ?{
?? ??? ?cout<<ret[i]<<endl;
?? ?}
?? ?
?? ?return 0;
}

C++ 實現字符串分割函數 split

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

vector<string> split( strData )
{
vector<string> vecData;
int nPos = strData.find( "," );
    while( nPos > 0 )
    {
        strTmp = strLine.substr( 0, nPos );
        vecData.push_back( strTmp );

        strLine.erase( 0, nPos+1 );
        nPos = strData.find( "," );
    }
vecData.push_back( strData );
    return vecData;
}

原文鏈接:https://blog.csdn.net/liangzhao_jay/article/details/87782017

欄目分類
最近更新