【模板小程序】字符串截取
1 /* 2 本程序说明: 3 4 字符串截取,如字符串qwer kkk/f/lsj sdfgh pppi/uhgf根据"/"分割为qwer kkk、f、lsj sdfgh pppi、uhgf 5 6 */ 7 #include <iostream> 8 #include <vector> 9 #include <string> 10 11 using namespace std; 12 13 //字符串截取 14 vector<string> split_string(const string& str, const string& pattern) 15 { 16 vector<string> resVec; 17 18 if ("" == str) 19 { 20 return resVec; 21 } 22 23 int index_start=0; 24 size_t pos = str.find(pattern,index_start); 25 while(pos!=string::npos) 26 { 27 resVec.push_back(str.substr(index_start,pos-index_start)); 28 index_start=(pos+=pattern.length()); 29 pos = str.find(pattern,index_start); 30 } 31 //截取最后一个 32 resVec.push_back(str.substr(index_start,str.length()-index_start)); 33 34 return resVec; 35 } 36 37 int main() 38 { 39 //测试样例 40 //vector<string> resVec=split_string("qwer kkkflsj sdfgh pppiuhgf"," "); 41 //vector<string> resVec=split_string("qwer kkk/f/lsj sdfgh pppi/uhgf","/"); 42 vector<string> resVec=split_string("qwer","/"); 43 for(auto val:resVec) 44 cout<<val<<endl; 45 46 return 0; 47 }
『注:本文来自博客园“小溪的博客”,若非声明均为原创内容,请勿用于商业用途,转载请注明出处http://www.cnblogs.com/xiaoxi666/』