天天看點

split函數與strtok函數的實作

#if 0
//..................split()函數
/*vector<string>split(const string &s,const string &seperator);*/
 /*輸入一個字元串,一個分隔符字元串(可包含多個分隔符)傳回一個字元串向量*/

vector<string>split(const string &s,const string &seperator)
{
    vector<string>result;
     int seplen = seperator.size();//計算分隔字元串的長度
     int pos = ;
     int index = -;
     /*size_t find(const string &str,size_t pos);
      從string 的pos位置尋找,str是要尋找的字元串
      函數傳回字元串第一次出現的位置 */
    while(- !=(index = s.find(seperator,pos)))
    {
        /*substr(size_type_Off,size_type_Count = npos)const;
        複制子字元串,從指定位置開始,有指定的長度
        _Off:begin pos _Count :所複制的字元數目*/
        result.push_back(s.substr(pos,index-pos));
        pos = index+seplen;

    }
    string laststring = s.substr(pos); //最後一個分隔符後面的内容
    if(!laststring.empty())
        result.push_back(laststring);
        return result;
}
int main()
{
    string s = "qq,sd,adscc,sdefde,sadse,adsdece";
    string sep = ",";
//  string s = "aaa,*bbed,*swq,*dfsdsd,*sqwsxx,*cc,*saas";
//  string sep = ",*";
    vector<string>v = split(s,sep);
    for(vector<string>::size_type i = ;i!=v.size();++i)
        cout<<v[i]<<" ";
    cout<<endl;

}

#endif
//...............strtok()函數
#if 0
/*char *strtok(char *str,const char *delim);*/
int main()
{
    char buf[] = "hello-I-am-a-girl*I-like*listen-music";
    char *sep = "-*";  //可以按多個字元分割
    char *temp = strtok(buf,sep);
    while(temp)
    {
        printf("%s ",temp);
        temp = strtok(NULL,sep);
    }
    printf("\n");
    return ;
}
#endif
           

繼續閱讀