【轉】C++ 分割字符串兩種方法


原文地址:http://blog.csdn.net/xjw532881071/article/details/49154911

 

字符串切割的使用頻率還是挺高的,string本身沒有提供切割的方法,但可以使用stl提供的封裝進行實現或者通過c函數strtok()函數實現。

1、通過stl實現

涉及到string類的兩個函數find和substr: 
1、find函數 
原型:size_t find ( const string& str, size_t pos = 0 ) const; 
功能:查找子字符串第一次出現的位置。 
參數說明:str為子字符串,pos為初始查找位置。 
返回值:找到的話返回第一次出現的位置,否則返回string::npos

2、substr函數 
原型:string substr ( size_t pos = 0, size_t n = npos ) const; 
功能:獲得子字符串。 
參數說明:pos為起始位置(默認為0),n為結束位置(默認為npos) 
返回值:子字符串 
代碼如下:

復制代碼
 1 std::vector<std::string> splitWithStl(const std::string &str,const std::string &pattern)
 2 {
 3     std::vector<std::string> resVec;
 4 
 5     if ("" == str)
 6     {
 7         return resVec;
 8     }
 9     //方便截取最后一段數據
10     std::string strs = str + pattern;
11 
12     size_t pos = strs.find(pattern);
13     size_t size = strs.size();
14 
15     while (pos != std::string::npos)
16     {
17         std::string x = strs.substr(0,pos);
18         resVec.push_back(x);
19         strs = strs.substr(pos+1,size);
20         pos = strs.find(pattern);
21     }
22 
23     return resVec;
24 }
復制代碼

2、通過使用strtok()函數實現

原型:char *strtok(char *str, const char *delim); 
功能:分解字符串為一組字符串。s為要分解的字符串,delim為分隔符字符串。 
描述:strtok()用來將字符串分割成一個個片段。參數s指向欲分割的字符串,參數delim則為分割字符串,當strtok()在參數s的字符串中發現到參數delim的分割字符時 則會將該字符改為\0 字符。在第一次調用時,strtok()必需給予參數s字符串,往后的調用則將參數s設置成NULL。每次調用成功則返回被分割出片段的指針。

其它:strtok函數線程不安全,可以使用strtok_r替代。 
代碼如下:

復制代碼
vector<string> split(const string &str,const string &pattern)
{
    //const char* convert to char*
    char * strc = new char[strlen(str.c_str())+1];
    strcpy(strc, str.c_str());
    vector<string> resultVec;
    char* tmpStr = strtok(strc, pattern.c_str());
    while (tmpStr != NULL)
    {
        resultVec.push_back(string(tmpStr));
        tmpStr = strtok(NULL, pattern.c_str());
    }

    delete[] strc;

    return resultVec;
}
復制代碼


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM