用C++ STL替换strtok_r

/* Parse S into tokens separated by characters in DELIM. 
   If S is NULL, the saved pointer in SAVE_PTR is used as 
   the next starting point.  For example: 
        char s[] = "-abc-=-def"; 
        char *sp; 
        x = strtok_r(s, "-", &sp);      // x = "abc", sp = "=-def" 
        x = strtok_r(NULL, "-=", &sp);  // x = "def", sp = NULL 
        x = strtok_r(NULL, "=", &sp);   // x = NULL 
                // s = "abc\0-def\0" 
*/  
char *strtok_r(char *s, const char *delim, char **save_ptr) {  
    char *token;  
  
    if (s == NULL) s = *save_ptr;  
  
    /* Scan leading delimiters.  */  
    s += strspn(s, delim);  
    if (*s == '\0')   
        return NULL;  
  
    /* Find the end of the token.  */  
    token = s;  
    s = strpbrk(token, delim);  
    if (s == NULL)  
        /* This token finishes the string.  */  
        *save_ptr = strchr(token, '\0');  
    else {  
        /* Terminate the token and make *SAVE_PTR point past it.  */  
        *s = '\0';  
        *save_ptr = s + 1;  
    }  
  
    return token;  
}  



----------改----------

char *split(char *s, const char *delim,char **save_ptr)

         stringresult;

    char *token; 

    if (s == NULL) s = *save_ptr; 

 

         if (*s == ‘\0’)

                   return NULL;

 

                  /* Scan leading delimiters.  */ 

         string temp = s;

             //s += strspn(s, delim);//替换 

size_t pos_1 = temp.find_first_not_of(delim, 0 );

    if (pos_1 == string::npos)  

        return NULL; 

                  //(s应该指过去,temp应该记个temp[pos])

                  /* Find the end of the token.  */ 

             //token =s; 

//s = strpbrk(token, delim);//替换 

size_t pos_2 = temp.find_first_of(delim,pos_1)

 

    if (pos_2 == string::npos

       /* This token finishes the string. */

                  result = s.substr(pos_1,);

                   strcpy(token, result.c_str());

 

       *save_ptr = s + temp.size(); 

    else

       /* Terminate the token and make *SAVE_PTR point past it.  */ 

       //*s = '\0'; 

                  result = temp.substr(pos_1,pos_2-pos_1);

                   strcpy(token, result.c_str());

       *save_ptr = s + pos_2+1;  

   } 

 

    return token; 

}  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值