First cnblogs article, I want to talk about splitting string.

I mainly use these fucntion in below method:

  string::find()

  string::size()

  string::substr()

some tips:

  string::npos

  size_t

I will supply a method firstly. This method can split string with only one pattern:

 1 //split string, with only one pattern
 2 vector<string> splitWithStl(const string &str,const string &pattern){
 3     vector<string> resVec;
 4     if("" == str){
 5         return resVec;//if string is null
 6     }
 7     string strs = str + pattern;
 8     size_t pos = strs.find(pattern);
 9     size_t size = strs.size();
10 
11     while(pos != string::npos){
12         string x = strs.substr(0,pos);//capture a length of string.
13         resVec.push_back(x);//push this stirng in vector
14         strs = strs.substr(pos+1,size);//get surplus string
15         pos = strs.find(pattern);//find next pattern
16     }
17     return resVec;
18 }

 

 

Next, I realize the method that can split string with some patterns:

 1 //split stirng, with some patterns
 2 string findNrstPt(const string &str,const string &pattern){//return nearest pattern
 3     size_t minPos = str.size();
 4     size_t pos = 0;
 5     string nstPt;
 6     nstPt = pattern[0];//intial pattern
 7     for(int i = 0; i < pattern.size(); i++){
 8         pos = str.find(pattern[i]);
 9         if((pos != 0) && (pos < minPos)){//if find the nearest pattern
10             minPos = pos;
11             nstPt = pattern[i];
12         }
13     }
14     return nstPt;
15 }
16 
17 vector<string> splitWithMtPt(const string &str, const string &pattern){//split string
18     vector<string> resVec;
19     if("" == str){
20         return resVec;
21     }
22     string strs = str + pattern[0];
23     //string strs = str;
24     string minPt = findNrstPt(strs,pattern);
25     size_t pos = strs.find(minPt);
26     size_t sizeStr = strs.size();
27     while(pos != string::npos){
28         string x = strs.substr(0,pos);//capture first string
29         resVec.push_back(x);//push string to result
30         strs = strs.substr(pos+1,sizeStr);//get surplus string
31         minPt = findNrstPt(strs,pattern);//find the nearst pattern
32         pos = strs.find(minPt);//find the next pattern location
33     }
34     return resVec;
35 }

 

posted @ 2017-08-30 17:07  JadeofMoon  阅读(82)  评论(0编辑  收藏  举报