C++11实现字符串分割的示例
时间:2022-04-16 10:01:07|栏目:C代码|点击: 次
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; }
上一篇:在动态库和静态库中使用模板(dynamic libraries ,static libraries)
栏 目:C代码
下一篇:深入内存对齐的详解
本文标题:C++11实现字符串分割的示例
本文地址:http://www.codeinn.net/misctech/199325.html