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;
}
到此这篇关于C++11实现字符串分割的示例的文章就介绍到这了,更多相关C++11 字符串分割内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!