原文地址: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 }
View Code

相关文章: