C++11實(shí)現(xiàn)字符串分割的示例
更新時間:2022年01月25日 10:56:00 作者:Mr_John_Liang
本文主要介紹了C++11實(shí)現(xiàn)字符串分割的示例,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
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++ 實(shí)現(xiàn)字符串分割函數(shù) 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;
}到此這篇關(guān)于C++11實(shí)現(xiàn)字符串分割的示例的文章就介紹到這了,更多相關(guān)C++11 字符串分割內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解C標(biāo)準(zhǔn)庫堆內(nèi)存函數(shù)
在C/C++語言中,我們知道內(nèi)存分為這幾種:程序全局變量內(nèi)存、棧內(nèi)存、堆內(nèi)存。其中堆內(nèi)存就是通過malloc(new)來分配的內(nèi)存,本文我們來探討一下C標(biāo)準(zhǔn)庫堆內(nèi)存函數(shù)。2021-06-06
C語言循環(huán)隊(duì)列的表示與實(shí)現(xiàn)實(shí)例詳解
這篇文章主要介紹了C語言循環(huán)隊(duì)列的表示與實(shí)現(xiàn),對于數(shù)據(jù)結(jié)構(gòu)與算法的研究很有幫助,需要的朋友可以參考下2014-07-07

