首页 > 编程开发 > C类语言    日期:2022-08-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;
}

觉得上面的内容有用吗?快来点个赞吧!

点赞() 我要打赏

温馨提示 : 本站内容来自会员投稿以及互联网,所有源码及教程均为作者总结编辑,请大家在使用过程中提前做好备份,以免发生无法预知的错误,源码类教程请勿直接用于生产环境!

 可能感兴趣的文章