Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3232389
  • 博文数量: 346
  • 博客积分: 10189
  • 博客等级: 上将
  • 技术积分: 3125
  • 用 户 组: 普通用户
  • 注册时间: 2008-08-05 19:46
文章分类

全部博文(346)

文章存档

2013年(35)

2011年(35)

2010年(76)

2009年(48)

2008年(152)

分类: C/C++

2008-08-29 13:46:30

   最近在做一个项目,要求代码跨平台,因此要使用标准C++。其中要用到字符串分割,在网上找了一下,对其进行稍作修改可以实现字符串任意分割,如下程序,并有使用举例。
#include
#include
#include
#include
using namespace std;

typedef basic_string::size_type S_T;  
static const S_T npos = -1;  

////trim指示是否保留空串,默认为保留。tok可以为任意多个字符
vector tokenize(const string& src, string tok,            
                        bool trim=false, string null_subst="")  
{  
    if( src.empty() || tok.empty() )
        throw "tokenize: empty string\0";  
        
    vector v; 
    S_T pre_index = 0, index = 0, len = 0; 
    while( (index = src.find_first_of(tok, pre_index)) !=npos ) 
    { 
        if( (len = index-pre_index)!=0 ) 
            v.push_back(src.substr(pre_index, len)); 
        else if(trim==false) 
            v.push_back(null_subst); 
        pre_index = index+1; 
    } 
    string endstr = src.substr(pre_index); 
    if( trim==false ) v.push_back( endstr.empty()?null_subst:endstr ); 
    else if( !endstr.empty() )
        v.push_back(endstr); 
    return v; 
}
//delimit为一个字符,严格分割
vector split(const string& src, string delimit, string null_subst="") 

    if( src.empty() || delimit.empty() )
        throw "split:empty string\0";   
    vector v; 
    S_T deli_len = delimit.size(); 
    long index = npos, last_search_position = 0; 
    while( (index=src.find(delimit,    
        last_search_position))!=npos ) 
    { 
        if(index==last_search_position) 
            v.push_back(null_subst); 
        else 
            v.push_back( src.substr(last_search_position, index-  
            last_search_position) ); 
        last_search_position = index + deli_len; 
    } 
    string last_one = src.substr(last_search_position); 
    v.push_back( last_one.empty()? null_subst:last_one ); 
    return v; 
}  

测试如下:
int main(int argc, char* argv[])
{
    string src = ",ab,cde;,,fg,," ; 
    string tok = ",;" ;  
    vector v1 = tokenize(src, tok ,true); 
    vector v2 = tokenize(src, tok ,false,    
        "");   
    cout<<"-------------v1:"<    for(int i=0; i    { 
        cout<    }  
    cout<<"-------------v2:"<    for(int j=0; j    { 
        cout<    } 
    try{ 
       
        string s = "1;2;3;4"; 
        string del = ";";//"###"; 
        vector v3 = split(s, del, ""); 
        cout<<"-------------v3:"<        for(int k=0; k        { 
            cout<        } 
    } 
    catch (char *s) { 
        cout<    }
    return 0;
}
阅读(17572) | 评论(2) | 转发(2) |
给主人留下些什么吧!~~

chinaunix网友2011-07-30 19:35:37

很好额,谢了!

feifei20012011-06-01 14:17:27

不错!